ObservableDictionary绑定到组合框显示值(MVVM)

时间:2015-03-20 22:42:32

标签: c# wpf xaml mvvm combobox

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

此外,Combobox ItemSource更改取决于之前ComboBox选择的内容。而且那也就是MVVM模式。有一个模型和视图模型。

我尝试设置DisplayPath等。但我无法在连击上显示字符串。始终看到[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}"/>

3 个答案:

答案 0 :(得分:2)

您需要设置以下属性(我假设您的ObservableDictionary继承自IDictionary<TKey, TValue>):

SelectedValuePath="Key" DisplayMemberPath="Value"

我已使用ObservableDictionary<TKey, TValue>

this实施进行了测试

在我的观点中:

<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; }
    }
}

答案 1 :(得分:1)

试试这个:

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

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

答案 2 :(得分:0)

假设您的类型“ObservableDictionary”是来自Dictionary的普通或不合理的,您可以绑定组合框中的显示和值。

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

如果用户没有添加或删除项目,我建议使用简单的List<YourClass>

相关问题