wpf - 如何将 ComboBox 的 SelectedItem 绑定(bind)到作为 ItemsSource 中项目副本的对象?

标签 wpf xaml mvvm data-binding combobox

我在 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 选择正确的项目?

最佳答案

您可能没有覆盖 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();
    }
}

关于wpf - 如何将 ComboBox 的 SelectedItem 绑定(bind)到作为 ItemsSource 中项目副本的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34140431/

相关文章:

c# - 如何在运行时更改 WPF 控件绑定(bind)

wpf - 使用 MVVM 将 TextBox 绑定(bind)到 WPF 中的大字符串

c# - 更改 ComboBox 的验证样式 WPF

c# - 不支持 WPF 调用脚本?

c# - 仅加载特定操作系统版本的样式

vb.net - Windows 10通用应用程序VB.NET在页面之间传递数据

c# - 在 C# 中打开目录选择器

WPF+MVVM : How to use plain old ViewModelBase when DependencyProperty is needed

WPF Stretch ListBox Height 100% of Grid.Row?

C# MVVM : Edit a SelectedItem of an ObservableCollection with a RelayCommand