即使在ItemsSource中缺少绑定值,Combobox也应显示绑定值 [英] Combobox should display bound value even if it's missing in ItemsSource

查看:100
本文介绍了即使在ItemsSource中缺少绑定值,Combobox也应显示绑定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WinForms组合框的情况下,即使其数据源中不存在绑定值,组合框仍将显示值(不是描述)。

In case of WinForms combobox, even if the bound value was not present in its datasource, the combobox would still show the value (not the description).

但是,在类似的情况下,Wpf组合框是空白的。为什么WPF中缺少此功能?我检查了组合框的代码 - 如果ItemsSource集合中不存在该项,则它不会设置SelectedValue。

However, the Wpf combobox is blank in a similar case. Why is this feature missing in WPF? I checked the code for combobox - it doesn't set the SelectedValue if the item doesn't exist in the ItemsSource collection.

总结:如果绑定值(例如:6)不是在数据源中找到,

To summarize: If bound value (eg: 6) is not found in datasource,

WinForms组合框:

WinForms combobox:


  • SelectedItem = null
  • SelectedValue = 6
  • Text =" 6"

WPF组合框:


  • SelectedItem = null
  • SelectedValue = null
  • Text = null

在这种特殊情况下,如何让WPF组合框像winforms组合框一样工作?

How can I make WPF combobox work like winforms combobox in this particular case?

推荐答案

以下XAML

<ComboBox
   IsEditable="True"
   ItemsSource="{Binding Path=Texts}"
   SelectedItem="{Binding Path=SelectedTextI}"
   SelectedValue="{Binding Path=SelectedTextV}"
   Text="{Binding Path=Text}" />

结合DataContext,如

combined with a DataContext like

 public class ViewModel
 {
    public ViewModel()
    {
       this.Texts = new List<string> { "one","two","three" };
    }

    public string SelectedTextI { get; set; }
    public string SelectedTextV { get; set; }
    public string Text { get; set; }
    public List<string> Texts { get; set; }
 }

产生ViewModel.Text,无论你在ComboBox中输入什么内容。

yields to ViewModel.Text whatever you type in the ComboBox.

干杯
$ b $bJürgen

Cheers
Jürgen


这篇关于即使在ItemsSource中缺少绑定值,Combobox也应显示绑定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆