I have a listbox where I bind the ItemsSource to a collection stored in the set DataContext object. This makes the list displayed using the ToString() function.
<ListBox ItemsSource="{Binding SomeCollection}"></ListBox>
Now I want to display a property for the objects in the collection instead. So I want to define a template etc to do this on all the objects in the bound list. I tried a variety of different approaches without success. I'd like to do something like this:
<ListBox ItemsSource="{Binding SomeCollection}">
<ListBox.Template>
<ControlTemplate>
<ListViewItem Content="{Binding ThePropertyOnElm}"></ListViewItem>
</ControlTemplate>
</ListBox.Template>
</ListBox>
Can anyone help me make this right?
you don't need to specify a template, you can just use the DisplayMemberPath property, like so:
<ListBox ItemsSource="{Binding SomeCollection}" DisplayMemberPath="ThePropertyOnElm" />
hope this helps!
I think this is what youre wanting to do:
<ListBox ItemsSource="{Binding SomeCollection}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:YourDataType}">
<TextBlock Text="{Binding ThePropertyOnElm}" />
</ControlTemplate>
</ListBox.ItemTemplate>
</ListBox>
The Template for the ListBox is going to modify how the actual listbox looks, and itemtemplate is going to control how the individual items in the listbox will look. I changed the controltemplate into a DataTemplate and assigned it to the type of YourDataType. Also, I used a textblock within the data template instead of listboxitem since the datatemplate is being assigned to the listboxitem (which should contain some type of content instead of another listboxitem).
i havent tried compiling this so it might not be exactly correct. if it doesnt let me know and ill take the extra steps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With