WPF通知对象的更改

时间:2010-05-27 06:09:22

标签: wpf

我有一个gridview,我定义了一些列,就像这样......

<GridViewColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding MyProp}" />
    </DataTemplate>
</GridViewColumn.CellTemplate>

我将gridview绑定到一个集合,并在属性MyProp中实现INotifyPropertyChanged。这很有效,MyProp的任何更改都会反映到gridview中。

如果我添加另一个绑定到对象本身的列,我就不会收到任何通知/更新。我的代码......

<GridViewColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding Converter={StaticResource myConverter}}"/>
    </DataTemplate>
</GridViewColumn.CellTemplate>

我认为我需要像对象的INotifyPropertyChanged,但我不知道如何做到这一点。有什么建议吗?

2 个答案:

答案 0 :(得分:5)

是的,实际的实例本身永远不会改变 - 只有它的属性。

据推测,你的转换器依赖于你绑定的对象的一堆属性?如果是这样,您可以使用MultiBinding并将转换器更改为IMultiValueConverter。然后,您可以绑定到可能导致TextBlock更新的所有依赖属性。

答案 1 :(得分:0)

使对象实现成为接口INotifyPropertyChanged

以下是来自MSDN的示例

public class DemoCustomer : INotifyPropertyChanged
{
// These fields hold the values for the public properties.
private Guid idValue = Guid.NewGuid();
private string customerName = String.Empty;
private string companyNameValue = String.Empty;
private string phoneNumberValue = String.Empty;

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

// The constructor is private to enforce the factory pattern.
private DemoCustomer()
{
    customerName = "no data";
    companyNameValue = "no data";
    phoneNumberValue = "no data";
}

// This is the public factory method.
public static DemoCustomer CreateNewCustomer()
{
    return new DemoCustomer();
}

// This property represents an ID, suitable
// for use as a primary key in a database.
public Guid ID
{
    get
    {
        return this.idValue;
    }
}

public string CompanyName
{
    get {return this.companyNameValue;}

    set
    {
        if (value != this.companyNameValue)
        {
            this.companyNameValue = value;
            NotifyPropertyChanged("CompanyName");
        }
    }
}
public string PhoneNumber
{
    get { return this.phoneNumberValue; }

    set 
    {
        if (value != this.phoneNumberValue)
        {
            this.phoneNumberValue = value;
            NotifyPropertyChanged("PhoneNumber");
        }
    }
}
}