如何将 ComboBox 的 SelectedItem 绑定到作为 ItemsSource 项目副本的对象? [英] How do you bind a ComboBox's SelectedItem to an object that is a copy of an item from ItemsSource?

查看:26
本文介绍了如何将 ComboBox 的 SelectedItem 绑定到作为 ItemsSource 项目副本的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WPF 中使用 MVVM 模式并遇到了一个问题,我可以将其简化为以下内容:

I'm using the MVVM pattern with WPF and have run into a problem, which I can simplify to the following:

我有一个 CardType 模型.

I have a CardType model.

public class CardType
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我有一个使用 CardType 的视图模型.

And I have a viewmodel that consumes 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,它的项目基于 CardType,并且应该基于 SelectedCardType 预选一个项目.

My XAML has a ComboBox that bases its items on CardTypes and should preselect an item based on SelectedCardType.

<ComboBox ItemsSource="{Binding CardTypes}"
          DisplayMemberPath="Name"
          SelectedItem="{Binding SelectedCardType}"/>

由于我无法控制的原因,SelectedCardType 对象将是 CardTypes 中项目的引用不相等副本.因此,WPF 无法将 SelectedItem 与 ItemsSource 中的项目匹配,并且当我运行该应用程序时,ComboBox 最初出现时未选择任何项目.

For reasons outside of my control, the SelectedCardType object will be a reference-unequal copy of the item in CardTypes. Therefore WPF fails to match the SelectedItem to an item in ItemsSource, and when I run the app, the ComboBox initially appears with no item selected.

我尝试覆盖 CardType 上的 Equals() 和 GetHashCode() 方法,但 WPF 仍然无法匹配项目.

I tried overriding the Equals() and GetHashCode() methods on CardType, but WPF still fails to match the items.

鉴于我的特殊限制,我怎样才能让 ComboBox 选择正确的项目?

Given my peculiar constraints, how can I get ComboBox to select the correct item?

推荐答案

您可能没有正确覆盖 EqualsGetHashCode.这应该对你有用.(但是,仅覆盖 Equals 将适用于您的情况,但当您覆盖类的 Equals 时,覆盖 GetHashCode 也被认为是一种很好的做法)

You might not be overriding Equals and GetHashCode properly. This should work for you. (However, just overriding Equals will work in your case but it's considered to be good practice to override GetHashCode too when you override Equals for a class)

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();
    }
}

这篇关于如何将 ComboBox 的 SelectedItem 绑定到作为 ItemsSource 项目副本的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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