如何在 WPF 中正确绑定 ListBoxItem?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/506495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly bind a ListBoxItem in WPF?
提问by Natrium
I have a listbox and I want to iterate over a collection of Bars in my Foo-object.
我有一个列表框,我想遍历我的 Foo 对象中的 Bars 集合。
<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 collectionof Bars is bound to the ContentControl, in stead of just 1.
如果我窥探(--> 使用工具 Snoop 检查)我的应用程序,我会注意到整个Bars集合都绑定到 ContentControl,而不仅仅是 1。
How can I properly bind so the iteration over the collection goes fine?
我怎样才能正确绑定,以便对集合的迭代正常进行?
回答by Cameron MacFarland
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.
您只需设置 DataTemplate,WPF 即可完成所有工作。将 ItemsSource 设置为Bar
项目列表,然后为Bar
项目定义 DataTemplate 。
<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>
您也可以直接使用<ListBox.ItemTemplate>
而不是设置 ItemsTemplate<ListBox.Resources>
See Data Binding Overviewat MSDN.
请参阅MSDN 上的数据绑定概述。
回答by belaz
First add your namespace to the Window
element (Intellisense) :
首先将您的命名空间添加到Window
元素 (Intellisense) 中:
xmlns:local="clr-namespace:yourenamespace"
Then the following XAML
( in Window.Resources
is a clean way to do it ) :
然后以下XAML
(inWindow.Resources
是一种干净的方法):
<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
:
<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
).
但是,这取决于您的代码隐藏对象,您必须设置一个构造函数来初始化对象中的公共属性,这些属性最好是ObservableCollection<>(对象实例中有一些限制规则XAML
)。