如何将ComboBox的SelectedItem绑定到作为ItemsSource项目副本的对象?

Bry*_*yan 9 data-binding wpf xaml combobox mvvm

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

我有一个CardType模型.

public class CardType
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个使用CardType的viewmodel.

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 ...
}
Run Code Online (Sandbox Code Playgroud)

我的XAML有一个ComboBox,它的项目基于CardTypes,应该根据SelectedCardType预选一个项目.

<ComboBox ItemsSource="{Binding CardTypes}"
          DisplayMemberPath="Name"
          SelectedItem="{Binding SelectedCardType}"/>
Run Code Online (Sandbox Code Playgroud)

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

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

鉴于我特有的限制,我如何让ComboBox选择正确的项目?

Roh*_*ats 9

你可能不被覆盖EqualsGetHashCode正确.这应该适合你.(但是,只重写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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Gia*_*rio 5

您可以使用 SelectedValue 和 SelectedValuePath:

<ComboBox ItemsSource="{Binding CardTypes}"
          DisplayMemberPath="Name"
          SelectedValue="{Binding ProductId, Mode=TwoWay}" 
          SelectedValuePath="Id"/>
Run Code Online (Sandbox Code Playgroud)

其中 ProductId 是一个带有 NotifyPropertyChanged 的​​ int 属性。

在这里阅读一个很好的解释: SelectedItem、SelectedValue 和 SelectedValuePath 之间的区别


Eam*_*ion 0

您可以执行的解决方法是将 SelectedItem 绑定到字符串(而不是 cardType),然后使用该字符串创建 CardType 类型的对象?