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

时间:2015-12-07 18:17:22

标签: wpf xaml mvvm data-binding combobox

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

我有一个CardType模型。

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

我有一个使用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 ...
}

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

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

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

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

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

3 个答案:

答案 0 :(得分:7)

您可能无法正确覆盖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();
    }
}

答案 1 :(得分:4)

您可以使用SelectedValue和SelectedValuePath:

<ComboBox ItemsSource="{Binding CardTypes}"
          DisplayMemberPath="Name"
          SelectedValue="{Binding ProductId, Mode=TwoWay}" 
          SelectedValuePath="Id"/>

其中ProductId是具有NotifyPropertyChanged的int属性。

在这里阅读一个很好的解释: Difference between SelectedItem, SelectedValue and SelectedValuePath

答案 2 :(得分:0)

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