如何在WPF C#中将组合框绑定到字典 [英] How To Bind a Combobox to a Dictionary in WPF C#

查看:84
本文介绍了如何在WPF C#中将组合框绑定到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将组合框绑定到字典,并在WPF中的当前选定对象中显示特定字段。

I'm trying to bind a combobox to a dictionary and display a specific field within the currently selected object in WPF.

我想要在组合框中显示的内容: (最初选择了我会做)

我会做

我不会做

我会做

What I want displayed in the combobox: ("I will do it" is initally selected)
I will do it
I will not do it
I might do it

当前实际显示的内容:(最初未选择任何内容)

[是,AnswerDisplayItem]

[否,AnswerDisplayItem ]

[MAYBE,AnswerDisplayItem]

What is actually displayed currently: (nothing is initally selected)
[YES, AnswerDisplayItem]
[No, AnswerDisplayItem]
[MAYBE, AnswerDisplayItem]

这是我的代码:

public enum Answer { YES, NO, MAYBE}

public class AnswerDisplayItem
{
    public string DisplayName { get; }
    public string DisplayDescription { get; }
    public AnswerDisplayItem(string displayName, string displayDescription)
    {
        DisplayName = displayName;
        DisplayDescription = displayDescription;
    }
}


public class MyViewModel()
{
    public MyViewModel() 
    {
        AnswerDisplay = new Dictionary<Answer, AnswerDisplayItem>
        {
            {Answer.YES, new AnswerDisplayItem("Yes", "I will do it") },
            {Answer.NO, new AnswerDisplayItem("No", "I will not do it")},
            {Answer.MAYBE, new AnswerDisplayItem("Maybe", "I might do it")}
        };
        SelectedAnswer = Answer.Yes;
    }


    public Dictionary<Answer, AnswerDisplayItem> AnswerDisplay{ get; private set; }

    private Answer _selectedAnswer;
    public Answer SelectedAnswer
    {
        get
        {
            return _selectedAnswer;
        }
        set
        {
            if (_selectedAnswer != value)
            {
                _selectedAnswer = value;
                RaisePropertyChanged();
            }
        }
    }
}

XAML :

<ComboBox ItemsSource="{Binding AnswerDisplay}" 
          DisplayMemberPath="Value.DisplayDescription"
          SelectedItem="{Binding SelectedAnswer}"/>


推荐答案

使用 Dictionary< Answer ,string> (不需要其他类)

AnswerDisplay = new Dictionary<Answer, string>
{
    {Answer.YES, "I will do it"},
    {Answer.NO,  "I will not do it"},
    {Answer.MAYBE, "I might do it"},
};

并将其绑定到 ComboBox

<ComboBox ItemsSource="{Binding AnswerDisplay}" 
          DisplayMemberPath="Value"
          SelectedValuePath="Key"
          SelectedValue="{Binding SelectedAnswer}"/>



更新



如果要使用您的字典,然后将绑定更改为

Update

If you want to use your dictionary, then change the binding to

<ComboBox ItemsSource="{Binding AnswerDisplay}" 
          DisplayMemberPath="Value.DisplayDescription"
          SelectedValuePath="Key"
          SelectedValue="{Binding SelectedAnswer}"/>

这篇关于如何在WPF C#中将组合框绑定到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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