如何使ListBox.ItemTemplate可重用/通用

Mat*_*ler 15 c# data-binding wpf itemtemplate

我试图了解如何最好地扩展ListBox控件.作为一个学习的经验,我想建立一个ListBoxListBoxItem场显示一个CheckBox,而不仅仅是文字.我使用了基本方式工作ListBox.ItemTemplate,明确设置我想要数据绑定的属性的名称.一个例子胜过千言万语,所以......

我有一个数据绑定的自定义对象:

public class MyDataItem {
    public bool Checked { get; set; }
    public string DisplayName { get; set; }

    public MyDataItem(bool isChecked, string displayName) {
        Checked = isChecked;
        DisplayName = displayName;
    }
}
Run Code Online (Sandbox Code Playgroud)

(我构建了一个列表并设置ListBox.ItemsSource为该列表.)我的XAML看起来像这样:

<ListBox Name="listBox1">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding Path=Checked}" Content="{Binding Path=DisplayName}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

这有效.但我想让这个模板可重用,即我想要绑定到除"Checked"和"DisplayName"以外的属性的其他对象.我如何修改我的模板,以便我可以使它成为一个资源,在多个ListBox实例上重用它,并为每个实例绑定IsCheckedContent任意属性名称?

MrT*_*lly 18

将DataTemplate创建为资源,然后使用ListBox的ItemTemplate属性引用它.MSDN有一个很好的例子

<Windows.Resources>
  <DataTemplate x:Key="yourTemplate">
    <CheckBox IsChecked="{Binding Path=Checked}" Content="{Binding Path=DisplayName}" />
  </DataTemplate>
...
</Windows.Resources>

...
<ListBox Name="listBox1"
         ItemTemplate="{StaticResource yourTemplate}"/>
Run Code Online (Sandbox Code Playgroud)


Bry*_*son 16

最简单的方法可能是把DataTemplate作为资源用在什么地方你的应用程序TargetTypeMyDataItem是这样

<DataTemplate DataType="{x:Type MyDataItem}">
    <CheckBox IsChecked="{Binding Path=Checked}" Content="{Binding Path=DisplayName}" />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

您可能还需要xmlns在本地程序集中包含一个并通过它引用它.然后,无论你使用一个ListBox(或其他任何使用MyDataItemContentPresenterItemsPresenter),它会用这个DataTemplate来显示它.