【问题标题】:Editable ComboBox with binding to value not in list绑定到不在列表中的值的可编辑组合框
【发布时间】:2011-04-14 04:24:40
【问题描述】:

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

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

现在绑定到 SelectedValue 的字符串只有在输入的值是 ComboBox 项中的一个时才会更新。

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

【问题讨论】:

    标签: .net wpf combobox editing


    【解决方案1】:

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

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

    【讨论】:

    • 哦,如果您不使用 ItemTemplate,您可以使用 DisplayMemberPath="Name" 而不是使用 DataTemplate。
    【解决方案2】:

    设置绑定到 Combo 的 Text 属性就足够了。

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

    【讨论】:

    • 非常适合绑定到字符串列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多