If I create a class that extends WPF’s ListBoxItem, create a list of these objects, try to bind the list to a ListBox’s ItemsSource, the items will not display:
<ListBox ItemsSource="{Binding Path=LbData, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">
<ListBox.ItemTemplate>
<DataTemplate >
<TextBlock Text="{Binding Path=Display}" Margin="1" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public partial class MainWindow : Window
{
public IEnumerable lbData = new List<LbItem>();
public IEnumerable LbData
{
get { return lbData; }
set { lbData = value; }
}
public MainWindow()
{
InitializeComponent();
LbData = new List<LbItem> { new LbItem("a"), new LbItem("b") };
}
}
public class LbItem : ListBoxItem
{
public string Display { get; private set; }
public LbItem(string v)
{
Display = v;
}
}
I’m new to WPF and don’t see why this should be an issue. TIA
The
ItemsSourcenormally is used for data-objects, and what you do there (setting theItemTemplate) suggest that you should not make your object inherit fromListBoxItemat all, instead it should be a normal object (possibly implementingINotifyPropertyChangedif properties may change after creation). If the list changes it should implementINotifyCollectionChanged.Because the items are already
ListBoxItemstheDataTemplateyou set will be disregarded. There should be the following error in your Visual Studio Output-window: