开发者

Use a user control as a DataTemplate within a WPF application

开发者 https://www.devze.com 2022-12-29 16:25 出处:网络
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 TextBlocks. This control also contains other shapes an

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 TextBlocks. 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.

W开发者_开发知识库hen 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>


That DataTemplate isn't actually being assigned to your ListBox. There's three ways:

1: Replace the template in the Resources section with

<ListBox.ItemTemplate>
    <DataTemplate>
        <local:ucActivityItm />
    </DataTemplate>
</ListBox.ItemTemplate>

in the ListBox.
2: Somewhat related:

<ListBox ... ItemTemplate="{StaticResource myActivity}">

3: Set the DataType parameter of the DataTemplate above to whatever the content of your ListBox is.

<DataTemplate x:Key="myActivity" DataType="{x:Type ...}">

I usually just do the first, but any should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消