【发布时间】:2017-05-24 00:11:29
【问题描述】:
我正在尝试将组合框绑定到字典并在 WPF 中当前选定的对象中显示特定字段。
我想在组合框中显示的内容:(“我会做”是最初选择的)
我会做的
我不会这样做
我可能会这样做
当前实际显示的内容:(最初没有选择任何内容)
[是,AnswerDisplayItem]
[不,AnswerDisplayItem]
[可能,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}"/>
【问题讨论】:
-
字典包含 KeyValuePair 的集合,该集合具有 Key 和 Value 属性。绑定该属性。顺便说一句 Dictionary
应该可以完成这项工作 -
这是我的意思,我不想使用字典
。我想要一个 AnswerDisplayItem,因为我需要在我的视图模型中访问其他字段。在这种情况下,无论我做什么,我似乎都无法正确绑定。 -
没有必要但可以使用字典
标签: c# wpf mvvm data-binding combobox