我在 WPF 中使用 MVVM 模式并遇到了问题,我可以将其简化为以下内容:
我有一个 CardType 模型。
public class CardType
{
public int Id { get; set; }
public string Name { get; set; }
}
我有一个使用 CardType 的 View 模型。
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 选择正确的项目?
最佳答案
您可能没有覆盖 Equals
和 GetHashCode
适本地。这应该适合你。 (但是,仅覆盖 Equals 将适用于您的情况,但是当您为类覆盖 Equals 时,覆盖 GetHashCode 也被认为是一种好习惯)
public class CardType
{
public int Id { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
CardType cardType = obj as CardType;
return cardType.Id == Id && cardType.Name == Name;
}
public override int GetHashCode()
{
return Id.GetHashCode() & Name.GetHashCode();
}
}
关于wpf - 如何将 ComboBox 的 SelectedItem 绑定(bind)到作为 ItemsSource 中项目副本的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34140431/