How To Bind a Combobox to a Dictionary in WPF C#

How To Bind a Combobox to a Dictionary in WPF C#

 

回答1

Use a Dictionary<Answer,string> (no need for another class)

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

and bind it to the 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}"/>

 

posted @ 2022-09-19 18:33  ChuckLu  阅读(143)  评论(0)    收藏  举报