【问题标题】:WPF ComboBox: Text value doesn't affect SelectedItemWPF ComboBox:文本值不影响 SelectedItem
【发布时间】:2014-12-04 12:55:52
【问题描述】:

如果我在 ComboBox 的依赖属性“Text”中加载字符串值。 ComboBox 没有将字符串值与 ItemsSource 对象配对,并且我没有填充 SelectedItem。

工具提示需要 SelectedItem!!

<ComboBox x:Name="FieldComboBox" IsEditable="True" IsTextSearchEnabled="True"                          
          Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
          DisplayMemberPath="DataCode" 
          ItemsSource="{Binding FieldAlternative.FieldParts[0].DataItems}"
          ToolTip="{Binding Path=SelectedItem.Description, ElementName=FieldComboBox}"/>     

如果我有空文本并写,它工作正常。如果我用 Text 中的值打开了表单,我的 SelectedItem 为 null,但会显示值 Text。

如何强制将 Text 与 ItemsSource 中的对象配对以填充 SelectedValue 的任何解决方案,或者我的问题的任何更好的解决方案。

谢谢

【问题讨论】:

    标签: c# wpf xaml combobox


    【解决方案1】:

    您可以通过 SelectedItem 属性为组合框设置默认值,该属性将绑定到 ViewModel 中的文本字段:

    SelectedItem="{Binding Path=Text, Mode=TwoWay}"
    

    所以你的组合框元素变成了这样:

    <ComboBox x:Name="FieldComboBox" IsEditable="True" IsTextSearchEnabled="True"                          
              Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
              SelectedItem="{Binding Path=Text, Mode=TwoWay}"
              DisplayMemberPath="DataCode" 
              ItemsSource="{Binding FieldAlternative.FieldParts[0].DataItems}"
              ToolTip="{Binding Path=SelectedItem.Description, ElementName=FieldComboBox}"/>
    

    【讨论】:

    • 它没有帮助。 SelectedItem 是对象 DataItem 并且 i|m 仅使用来自该对象的 DataCode 字符串来填充另一个对象(字段)的 Text 属性。所以 Bindint Text 是 Field.Text 而这个 CB 的来源是 DataItems。
    猜你喜欢
    • 2012-01-18
    • 2011-01-10
    • 2012-06-19
    • 1970-01-01
    • 2017-05-05
    • 2014-07-05
    • 2011-11-01
    • 2017-02-20
    • 2014-03-18
    相关资源
    最近更新 更多