WPF IsEditable=true 用对象填充的 ComboBox 将 ToString() 显示为所选项目 [英] WPF IsEditable=true ComboBox filled with objects displays the ToString() as the selected item

查看:59
本文介绍了WPF IsEditable=true 用对象填充的 ComboBox 将 ToString() 显示为所选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Wpf 组合框允许编辑,如果您的所有组合框项都是字符串,或者在其上定义了 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.

当您选择一个项目时,它显示为文本,它不使用 DataTemplate,它只是在所选项目上调用 ToString().

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.

我在我的组合下拉列表中得到一个使用我的项目模板格式化的项目列表,当我选择一个时,我得到对象的名称,即 MyNamespace.MyObjectName

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

一些解决方案已经

  • 使用 ValuePath 绑定到一个属性在对象上,但如果您需要您的展示不仅仅是其中之一这些,运气不好.
  • 在上实现 ToString() 方法你的对象

还有别的办法吗?

推荐答案

您可以完全在 Xaml 中执行此操作

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>

好处是您可以在 XAML 中随意定义和更改它,而无需任何代码隐藏.您将 ItemsSource 绑定到您的对象集合,然后将搜索的基础路径设置为 TextSearch.TextPath.然后,在您自定义的 ItemTemplate 中,您可以将 TextBlock 绑定到对象的 ToString 方法之外的其他内容.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆