sti*_*k81 12 .net wpf binding listbox
我有一个列表框,我将ItemsSource绑定到存储在集合DataContext对象中的集合.这使得使用ToString()函数显示列表.
<ListBox ItemsSource="{Binding SomeCollection}"></ListBox>
Run Code Online (Sandbox Code Playgroud)
现在我想显示集合中对象的属性.所以我想定义一个模板等来对绑定列表中的所有对象执行此操作.我尝试了各种不同的方法而没有成功.我想做这样的事情:
<ListBox ItemsSource="{Binding SomeCollection}">
<ListBox.Template>
<ControlTemplate>
<ListViewItem Content="{Binding ThePropertyOnElm}"></ListViewItem>
</ControlTemplate>
</ListBox.Template>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我做到这一点吗?
Roe*_*elF 32
您不需要指定模板,只需使用DisplayMemberPath属性,如下所示:
<ListBox ItemsSource="{Binding SomeCollection}" DisplayMemberPath="ThePropertyOnElm" />
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
Mar*_*iec 11
我想这就是你想要做的事情:
<ListBox ItemsSource="{Binding SomeCollection}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:YourDataType}">
<TextBlock Text="{Binding ThePropertyOnElm}" />
</ControlTemplate>
</ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
ListBox的模板将修改实际列表框的外观,而itemtemplate将控制列表框中各个项目的外观.我将controltemplate更改为DataTemplate并将其分配给YourDataType类型.此外,我在数据模板中使用了一个文本块而不是listboxitem,因为datatemplate被分配给listboxitem(它应该包含某种类型的内容而不是另一个listboxitem).
我还没有尝试过编译,所以它可能不完全正确.如果它不让我知道,并采取额外的步骤!