【问题标题】:ObservableDictionary binding to combobox display value(MVVM)ObservableDictionary 绑定到组合框显示值(MVVM)
【发布时间】:2015-05-24 11:25:10
【问题描述】:

我遇到了数据绑定问题。我有一个 WPF (MVVM) 用户控制项目。有ComboboxesLabels。每个ComboBox 绑定到一个ObservableDictionary<int,string>。所以我的问题是我只需要在我的ComboBox 上显示字典的字符串部分。

此外,Combobox ItemSource 的更改取决于在之前的 ComboBox 中选择的内容。这也是 MVVM 模式。有模型和视图模型。

我尝试设置DisplayPathetc。但我不能只显示连击的字符串。总是看到[0, sample][1,yes]

<ComboBox HorizontalAlignment="Left" Margin="250,15,0,0" VerticalAlignment="Top" Width="120" Name="CBxerisim" SelectionChanged="CBxerisim_SelectionChanged" ItemsSource="{Binding Derisimkodu}" />
<ComboBox HorizontalAlignment="Left" Margin="250,45,0,0" VerticalAlignment="Top" Width="120" Name="CBxteklifDurum" SelectionChanged="CBxteklifDurum_SelectionChanged" ItemsSource="{Binding Dteklifdurumu}"/>
<ComboBox HorizontalAlignment="Left" Margin="250,75,0,0" VerticalAlignment="Top" Width="120" Name="CBxteklifSonuc" SelectionChanged="CBxteklifSonuc_SelectionChanged" ItemsSource="{Binding Dteklifsonuc}"/>

【问题讨论】:

    标签: c# wpf xaml mvvm combobox


    【解决方案1】:

    您需要设置以下属性(我假设您的 ObservableDictionary 继承自 IDictionary&lt;TKey, TValue&gt;):

    SelectedValuePath="Key" DisplayMemberPath="Value"
    

    我已经使用this 实现ObservableDictionary&lt;TKey, TValue&gt; 进行了测试

    在我看来:

    <ComboBox Width="35" SelectedValuePath="Key" DisplayMemberPath="Value" ItemsSource ="{Binding FirstDictionary}"/>
    

    还有我的视图模型:

    public class ViewModel
    {
        private ObservableDictionary<int, string> _firstDictionary;
    
        public ViewModel()
        {
            _firstDictionary = new ObservableDictionary<int, string>()
                    {
                        new KeyValuePair<int, string>(1, "A"),
                        new KeyValuePair<int, string>(2, "B"),
                        new KeyValuePair<int, string>(3, "C")
                    };
        }
    
        public ObservableDictionary<int, string> FirstDictionary
        {
            get { return _firstDictionary; }
            set { _firstDictionary = value; }
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      <ComboBox DisplayMemberPath="Value"></ComboBox>
      

      您可以使用 SelectedValuePath-Attribute 以与属性名称相同的方式作为简单字符串(它不是常规绑定)。

      【讨论】:

        【解决方案3】:

        假设您的类型“ObservableDictionary”是一个普通的或从字典中继承的,您可以从组合框中绑定显示和值。

         comboBox.ItemsSource = dictionary; // your collection
         comboBox.SelectedValuePath = "Key"; // dictionary key
         comboBox.DisplayMemberPath = "Value"; // dictionary content
        

        如果用户不添加或删除项目,我建议使用简单的List&lt;YourClass&gt;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-13
          • 2018-06-12
          • 2015-09-15
          • 1970-01-01
          • 2013-01-07
          • 2021-10-11
          • 2015-07-11
          • 2015-04-27
          相关资源
          最近更新 更多