How to properly bind a ListBoxItem in WPF?
Solution 1
You can just set the DataTemplate, and WPF does all the work. Set the ItemsSource to a list of Bar
items, and then define a DataTemplate for Bar
items.
<ListBox ItemsSource="{Binding Path=Foo.Bars}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type Bar}">
<Label Content="hello stackoverflow" />
</DataTemplate>
</ListBox.Resources>
</ListBox>
You could also set the ItemsTemplate directly by using <ListBox.ItemTemplate>
instead of <ListBox.Resources>
See Data Binding Overview at MSDN.
Solution 2
First add your namespace to the Window
element (Intellisense) :
xmlns:local="clr-namespace:yourenamespace"
Then the following XAML
( in Window.Resources
is a clean way to do it ) :
<Window.Resources>
<ObjectDataProvider x:Key="DataProvider" ObjectType="{x:Type local:Foo}"/>
<DataTemplate x:Key="Template" >
<TextBlock Text="{Binding Bar}"/>
</DataTemplate>
</Window.Resources>
Place the Listbox
:
<ListBox DataContext="{Binding Source={StaticResource DataProvider}}" ItemsSource="{Binding Bars}" ItemTemplate="DynamicResource Template" />
But, it depends on your code-behind object, you have to set a constructor to initialise public properties within your object which are ObservableCollection<> preferably (There is some restriction rules with object instance in XAML
).
Related videos on Youtube
Comments
-
Natrium about 4 years
I have a listbox and I want to iterate over a collection of Bars in my Foo-object.
<ListBox DataContext="{Binding Path=Foo.Bars}" > <ListBox.Items> <ListBoxItem> <ContentControl DataContext="{Binding Path=.}" /> </ListBoxItem> </ListBox.Items> </ListBox>
This is the datatemplate I want to use.
<DataTemplate DataType="{x:Type Bar}"> <Label Content="hello stackoverflow" /> </DataTemplate>
If I snoop (--> examine by using the tool Snoop) my application, I notice that the entire collection of Bars is bound to the ContentControl, in stead of just 1.
How can I properly bind so the iteration over the collection goes fine?
-
belaz over 15 yearsI suggest you to type your object code in your question. There was some syntax error in my answer, i correct it ( Resource, not Resouce, forgotten GridView, i'am typing it all with the hand... ).
-
Cameron MacFarland about 11 years@Default Yeah, that link as rotted away and I can't find a replacement sorry. It was just an article talking about bindings in WPF.