.net 绑定到不在列表中的值的可编辑组合框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3743269/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:44:10  来源:igfitidea点击:

Editable ComboBox with binding to value not in list

.netwpfcomboboxediting

提问by ronag

I have editable combobox where not always the preferred item is in the drop-down list.

我有可编辑的组合框,其中并不总是首选项目在下拉列表中。

I would like to have the possibility of manually entering text in the textbox which is propagated to the string bound to SelectedValue.

我希望有可能在文本框中手动输入文本,该文本将传播到绑定到 SelectedValue 的字符串。

Right now the string bound to SelectedValue is only updated if the entered value is on of the ones in the ComboBox items.

现在,绑定到 SelectedValue 的字符串仅在输入的值是 ComboBox 项中的值时才会更新。

How do I allow custom values not available in the ComboBox list to be manually entered and properly propagated to bound value?

如何允许手动输入 ComboBox 列表中不可用的自定义值并正确传播到绑定值?

回答by John Gardner

I was just doing this yesterday and today and it looks like the following:

我昨天和今天都在做这个,它看起来像下面这样:

  1. set the combobox IsEditable="true"

  2. instead of binding to SelectedItem, bind to the Textproperty of the combobox

  3. if you're binding to a custom object instead of just strings, you need to also set TextSearch.TextPath="NameOfField". This lets the text search behavior work, and also shows this property in the textbox as well.

  1. 设置组合框 IsEditable="true"

  2. 而不是绑定到SelectedItem,绑定到Text组合框的属性

  3. 如果要绑定到自定义对象而不仅仅是字符串,则还需要设置TextSearch.TextPath="NameOfField". 这使文本搜索行为起作用,并且还在文本框中显示此属性。

All in all, I ended up with something like:

总而言之,我最终得到了类似的结果:

<ComboBox x:Name="c" 
          IsEditable="True" 
          IsTextSearchEnabled="True" 
          IsTextSearchCaseSensitive="False" 
          StaysOpenOnEdit="True"
          Text="{Binding NameOnViewModel}"
          TextSearch.TextPath="NameOnChildItems"  
          ItemsSource="{Binding Items}" 
          ItemTemplate="{StaticResource DataTemplate}" />

<TextBlock Text="{Binding ElementName=c,Path=Text}" />

回答by Rauld

Setting the binding to Text property of Combo will suffice as well.

将绑定设置为 Combo 的 Text 属性也足够了。

<ComboBox  IsTextSearchEnabled="True"    IsEditable="True" 
ItemsSource="{Binding Items}" Text="{Binding SelectedItemText, Mode=TwoWay}" />