在 WPF 应用程序中使用用户控件作为 DataTemplate
我正在尝试在 WPF 应用程序中创建一个用户控件,该控件将用作 ListBoxItem
的 DataTemplate
。用户控制一个带有 4 个 TextBlock 的网格。该控件还包含其他形状和图像,这些形状和图像更多地用于视觉辅助,因此为了清楚起见,我从这个问题的代码中省略了它们。
当我将用户控件放在 mainwindow.xaml 上时,我可以看到该控件和正确绑定的字段指向数据源中的第一条记录。我想要做的是让此控件在列表框或包装面板中为数据库中的每条记录重复呈现。
任何人都可以为我提供如何在 ListBox
控件/其他面板中将用户控件呈现为 DataTemplate
的指针或示例。
到目前为止,我已经尝试了以下方法,但没有成功: 预先感谢您的任何提示。
<!--within Window.Resource -->
<DataTemplate x:Key="myActivity">
<local:ucActivityItm /> <!--usercontrol -->
</DataTemplate>
<!-- Listbox within the window -->
<ListBox HorizontalAlignment="Stretch" ItemTemplate="{DynamicResource myActivity}" VerticalAlignment="Stretch">
<ListBoxItem>
<!-- control also added for testing to ensure it rendered out-->
<local:ucActivityItm />
</ListBoxItem>
</ListBox>
I am trying to create a user control within a WPF application that will serve as a DataTemplate
for a ListBoxItem
. The user control a grid with 4 TextBlock
s. This control also contains other shapes and images more for visual aid than anything so I am omitting them from the code in this question for clarity.
When I drop the user control on my mainwindow.xaml I can see the control and the properly bound fields point to the first record in the datasource. What I want to do is have this control render repeatedly within either a listbox or a wrap panel for each record within the database.
Can anyone provide me with a pointer or sample of how to have a user control render as a DataTemplate
within the ListBox
control/other panel.
Up to this point I have tried the following with no avail:
Thanks in advance for any tips.
<!--within Window.Resource -->
<DataTemplate x:Key="myActivity">
<local:ucActivityItm /> <!--usercontrol -->
</DataTemplate>
<!-- Listbox within the window -->
<ListBox HorizontalAlignment="Stretch" ItemTemplate="{DynamicResource myActivity}" VerticalAlignment="Stretch">
<ListBoxItem>
<!-- control also added for testing to ensure it rendered out-->
<local:ucActivityItm />
</ListBoxItem>
</ListBox>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该
DataTemplate
实际上并未分配给您的ListBox
。共有三种方法:1:将资源部分中的模板替换为
ListBox
中的模板。2:有些相关:
3:将上面的
DataTemplate
的 DataType 参数设置为ListBox
的内容。我通常只做第一个,但任何一个都应该有效。
That
DataTemplate
isn't actually being assigned to yourListBox
. There's three ways:1: Replace the template in the Resources section with
in the
ListBox
.2: Somewhat related:
3: Set the DataType parameter of the
DataTemplate
above to whatever the content of yourListBox
is.I usually just do the first, but any should work.