【发布时间】:2016-03-12 11:03:26
【问题描述】:
我在 WPF 中使用 MVVM 模式并遇到了问题,我可以将其简化为以下内容:
我有一个 CardType 模型。
public class CardType
{
public int Id { get; set; }
public string Name { get; set; }
}
我有一个使用 CardType 的视图模型。
public class ViewModel : INotifyPropertyChanged
{
private CardType selectedCardType;
public CardType SelectedCardType
{
get { return selectedCardType; }
set
{
selectedCardType = value;
OnPropertyChanged(nameof(SelectedCardType));
}
}
public IEnumerable<CardType> CardTypes { get; set; }
// ... and so on ...
}
我的 XAML 有一个 ComboBox,它的项目基于 CardTypes,并且应该根据 SelectedCardType 预先选择一个项目。
<ComboBox ItemsSource="{Binding CardTypes}"
DisplayMemberPath="Name"
SelectedItem="{Binding SelectedCardType}"/>
由于我无法控制的原因,SelectedCardType 对象将是 CardTypes 中项目的引用不相等副本。因此 WPF 无法将 SelectedItem 与 ItemsSource 中的项目匹配,当我运行应用程序时,ComboBox 最初出现时没有选择任何项目。
我尝试覆盖 CardType 上的 Equals() 和 GetHashCode() 方法,但 WPF 仍然无法匹配项目。
鉴于我的特殊限制,我怎样才能让 ComboBox 选择正确的项目?
【问题讨论】:
-
虽然票数最高的答案有效,但stackoverflow.com/a/24776204/1121033 是解决同一问题的更优雅的解决方案。
标签: wpf xaml mvvm data-binding combobox