1

假设我定义了一个类,如下所示。现在让我们说我进一步修改这个类以正确实现 NotifyPropertyChanged 并添加到我绑定到 WPF 网格的集合中。如果执行代码更改其中一个实例的 Name 或 Description 属性,其他实例也会更新吗?WPF/XAML 绑定是否将这些相同的对象视为相同的对象,还是将实例视为不同的并且仅更新已更改对象的属性?

class Security
{       
    public string Ticker { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null) return false;

        if (this.GetType() != obj.GetType()) return false;

        Security security = (Security)obj;

        //reference check
        //if (!Object.Equals(Ticker, security.Ticker)) return false;

        //value member check
        if (!Ticker.Equals(security.Ticker)) return false;

        return true;
    }

    public static bool operator ==(Security sec1, Security sec2)
    {
        if (System.Object.ReferenceEquals(sec1, sec2)) return true;

        if (((object)sec1 == null) || ((object)sec2 == null)) return false;

        // Return true if the fields match:
        return sec1.Ticker == sec2.Ticker;
    }

    public static bool operator !=(Security sec1, Security sec2)
    {
        return !(sec1 == sec2);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            // Suitable nullity checks etc, of course :)
            hash = hash * 23 + Ticker.GetHashCode();
            hash = hash * 23 + Ticker.GetHashCode();
            hash = hash * 23 + Ticker.GetHashCode();
            return hash;
        }
    }
}

4

1 回答 1

1

关于绑定如何工作的一个相当松散的描述是,xaml 类构建了一个它所绑定到的属性的查找表。当引发 PropertyChanged 事件时,xaml 类检查它的查找表以查找与参数匹配的属性并刷新该值。因此,只会更新在 PropertyChanged 事件中传递名称的属性的值。

一个实现如下所示:

class Security : INotifyPropertyChanged
{   
    public event PropertyChangedEventHandler PropertyChanged;

    public string Ticker 
    { 
        get { return ticker; } 
        set { 
               ticker = value; 
               PropertyChanged(this, new PropertyChangedEventArgs("Ticker"));
        }
    }

    ...// implement the rest of your class like above
 }

有关更多信息,请参阅此处此处的INotifyPropertyChanged 文档。

于 2012-05-05T02:54:22.757 回答