如何在WPF中正确绑定ListBoxItem?
我有一个列表框,我想迭代我的Foo对象中的一组条如何在WPF中正确绑定ListBoxItem?,wpf,data-binding,xaml,listview,Wpf,Data Binding,Xaml,Listview,我有一个列表框,我想迭代我的Foo对象中的一组条 <ListBox DataContext="{Binding Path=Foo.Bars}" > <ListBox.Items> <ListBoxItem> <ContentControl DataContext="{Binding Path=.}" /> </ListBoxItem> </ListBox.It
<ListBox DataContext="{Binding Path=Foo.Bars}" >
<ListBox.Items>
<ListBoxItem>
<ContentControl DataContext="{Binding Path=.}" />
</ListBoxItem>
</ListBox.Items>
</ListBox>
这是我要使用的数据模板
<DataTemplate DataType="{x:Type Bar}">
<Label Content="hello stackoverflow" />
</DataTemplate>
如果我使用工具snoop(->检查)我的应用程序,我会注意到整个条集合绑定到ContentControl,,而不是仅1条
如何正确绑定以使集合上的迭代顺利进行?首先将名称空间添加到
窗口
元素(Intellisense):
然后,下面的XAML
(在窗口中。参考资料
是一种干净的方法):
但是,这取决于您的代码隐藏对象,您必须设置一个构造函数来初始化对象内的公共属性,这些属性最好是(在
XAML
中有一些对象实例的限制规则)。您只需设置数据模板,WPF就可以完成所有工作。将项目资源设置为Bar
项目列表,然后为Bar
项目定义数据模板
<ListBox ItemsSource="{Binding Path=Foo.Bars}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type Bar}">
<Label Content="hello stackoverflow" />
</DataTemplate>
</ListBox.Resources>
</ListBox>
您还可以使用
而不是
直接设置ItemsTemplate
请参阅MSDN。我建议您在问题中键入目标代码。我的答案中有一些语法错误,我改正了(Resource,而不是Resource,忘记了GridView,我正在用手打字…),实际上我使用的是一个列表框。我第一次发布ListView,但我编辑了它。@Default是的,那个链接已经坏掉了,我找不到替换的链接。对不起。这只是一篇关于WPF中绑定的文章。
<Window.Resources>
<ObjectDataProvider x:Key="DataProvider" ObjectType="{x:Type local:Foo}"/>
<DataTemplate x:Key="Template" >
<TextBlock Text="{Binding Bar}"/>
</DataTemplate>
</Window.Resources>
<ListBox DataContext="{Binding Source={StaticResource DataProvider}}" ItemsSource="{Binding Bars}" ItemTemplate="DynamicResource Template" />
<ListBox ItemsSource="{Binding Path=Foo.Bars}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type Bar}">
<Label Content="hello stackoverflow" />
</DataTemplate>
</ListBox.Resources>
</ListBox>