Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

WPF IsEditable=true ComboBox filled with objects displays the ToString() as the selected item

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...