c# - ObservableDictionary 绑定(bind)到组合框显示值(MVVM)

标签 c# wpf xaml mvvm combobox

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

另外,Combobox ItemSource更改取决于之前选择的内容 ComboBox .这也是 MVVM 模式。有模型和 View 模型。

我尝试设置 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}"/>

还有我的 View 模型:

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

关于c# - ObservableDictionary 绑定(bind)到组合框显示值(MVVM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29176922/

相关文章:

wpf - 在 WPF 中跨 ViewModel 共享模型的最佳/推荐方式是什么?

WPF:当我将代码移动到另一个 DLL 中时,不再调用 OnApplyTemplate

xaml - 图像填充按钮 UWP Xaml

c# - UWP、XAML - 使 CheckBox 为空

c# - 如何禁用 gridview 命令字段控件中的控件

c# - 蓝牙串行端口 (SPP) 传入端口创建

c# - 如何设计用于批量插入和更新的 Restful API?

WPF 数据网格 : How do I databind the properties of the SelectedItem to trigger INotifyPropertyChangedEvents?

xaml - XmlnsDefinitionAttribute 和不明确的类型

c# - 计算最频繁的元素