可编辑组合框,绑定到列表中未包含的值

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

我希望能够在文本框中手动输入文本,然后将其传播到绑定到 SelectedValue 的字符串。

现在,绑定到 SelectedValue 的字符串只有在输入的值位于 ComboBox 项中的值之上时才会更新。

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

49976 次浏览

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 Text property 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.

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}" />

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

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