具有绑定到值的可编辑ComboBox不在列表中

ron*_*nag 80 .net wpf combobox editing

我有可编辑的组合框,其中并不总是首选项位于下拉列表中.

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

现在,只有在ComboBox项目中输入的值为on时,才会更新绑定到SelectedValue的字符串.

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

Joh*_*ner 128

我昨天和今天只是这样做,它看起来如下:

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

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

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

总而言之,我最终得到了类似的东西:

<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}" />
Run Code Online (Sandbox Code Playgroud)

  • 哦,如果你没有使用ItemTemplate,你可以使用DisplayMemberPath ="Name"而不是使用DataTemplate. (4认同)

Rau*_*uld 28

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

<ComboBox  IsTextSearchEnabled="True"    IsEditable="True" 
ItemsSource="{Binding Items}" Text="{Binding SelectedItemText, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)