I am trying to understand how best to extend the ListBox
control. As a learning experience, I wanted to build a ListBox
whose ListBoxItem
s display a CheckBox
instead of just text. I got that working in a basic fashion using the ListBox.ItemTemplate
, explicitly setting the names of the properties I wanted to databind to. An example is worth a thousand words, so...
I've got a custom object for databinding:
public class MyDataItem {
public bool Checked { get; set; }
public string DisplayName { get; set; }
public MyDataItem(bool isChecked, string displayName) {
Checked = isChecked;
DisplayName = displayName;
}
}
(I build a list of those and set ListBox.ItemsSource
to that list.) And my XAML looks like this:
<ListBox Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Checked}" Content="{Binding Path=DisplayName}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This works. But I want to make this template reusable, i.e. I'll want to bind to other objects with properties other than "Checked" and "DisplayName". How can I modify my template such that I could make it a resource, reuse it on multiple ListBox
instances, and for each instance, bind IsChecked
and Content
to arbitrary property names?