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

ObservableDictionary binding to combobox display value(MVVM)

我的数据绑定有问题。我有一个 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}"/>

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

SelectedValuePath="Key" DisplayMemberPath="Value"

我已经使用 this 实现 ObservableDictionary<TKey, TValue>

进行了测试

在我看来:

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

试试这个:

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

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

假设您的类型 "ObservableDictionary" 是字典中的普通类型或不规则类型,您可以从组合框中绑定显示和值。

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

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