WPF IsEditable = true填充对象的ComboBox将ToString()显示为所选项目 [英] WPF IsEditable=true ComboBox filled with objects displays the ToString() as the selected item
问题描述
Wpf组合框允许进行编辑,如果所有的组合框项目都是字符串,或者定义了ToString()方法,那么这是很好的。
你选择一个项目,它显示为Text,它不使用DataTemplate,它只是调用ToString()选择的项目。
我得到我的组合下拉列表中使用我的项目模板格式化的项目列表,当我选择一个,我得到对象的名称 MyNamespace .MyObjectName
一些解决方案已经
- 绑定到对象上的属性
,但是如果你需要
,你的显示为多于
这些,运气不好。 - 实现
上的ToString()方法您的对象
有另一种方法吗?
< ComboBox IsTextSearchEnabled =TrueIsEditable =True
ItemsSource ={Binding MyObjectCollection}
TextSearch.TextPath =MyObjectName>
< ComboBox.ItemTemplate>
< DataTemplate>
< TextBlock Text ={Binding MyObjectName}/>
< / DataTemplate>
< /ComboBox.ItemTemplate>
< / ComboBox>上面是你可以在你的XAML中定义和改变这个,而不需要任何代码隐藏。 。您将ItemsSource绑定到对象的集合,然后设置将搜索的基础的路径到TextSearch.TextPath。然后,在你自定义的ItemTemplate中,你可以将TextBlock绑定到对象的ToString方法之外的其他东西。
The Wpf combo box allows editing, and this is fine if all your combo box items are strings, or have a ToString() method defined on them.
When you select an item, it is displayed as Text, it does not use a DataTemplate, it just calls ToString() on the item that is selected.
I get a list of items in my combo drop down that are formatted using my item template, when i select one i get the name of the object i.e. MyNamespace.MyObjectName
Some solutions have been
- use ValuePath to bind to a property
on the object, but if you require
your display to be more than one of
these, bad luck.
- implement the ToString() method on
your object
is there another way around?
解决方案 You can do this entirely within Xaml
<ComboBox IsTextSearchEnabled="True" IsEditable="True"
ItemsSource="{Binding MyObjectCollection}"
TextSearch.TextPath="MyObjectName">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding MyObjectName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
The upside is that you can define and change this however you want in your XAML without any code-behind. You bind the ItemsSource to your collection of objects, and then you set the path on which to base your search to TextSearch.TextPath. Then, within you custom ItemTemplate you can bind the TextBlock to something else outside of the object's ToString method.
这篇关于WPF IsEditable = true填充对象的ComboBox将ToString()显示为所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!