设置数据上下文

时间:2013-11-21 10:33:56

标签: c# json data-binding windows-8 datacontext

我遇到了下一个问题:

我有来自服务器的JSON文件和一些数据。我写了一个类,允许我反序列化JSON:

public class Person : INotifyPropertyChanged
{
    //public event PropertyChangedEventHandler PropertyChanged;
    public int? version { get; set; }
    public int? id { get; set; }
    public string name { get; set; }
    public bool? isNeeded { get; set; }

    //protected void OnPropertyChanged(string name)
    //{
    //    PropertyChangedEventHandler handler = PropertyChanged;
    //    if (handler != null)
    //    {
    //        handler(this, new PropertyChangedEventArgs(name));
    //    }
    //}
}

我有一个自定义控件,我将DataContext设置为Person - 绑定工作,但我想控制在某些字段(1或多个)被修改时作出反应。

1)我是否必须将PropertyChanged写入每个属性?

我设法写了这个:

public class Person : INotifyPropertyChanged
{
    private string _name;
    public event PropertyChangedEventHandler PropertyChanged;
    public int? version { get; set; }
    public int? id { get; set; }
    public string name 
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged("name");
        }
    }
    public bool? isNeeded { get; set; }

    protected void OnPropertyChanged(string _name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(_name));
        }
    }
}

但问题是我应该为每个属性创建私有变量,我应该为每个属性编写EventChanged吗?或者有一种更简单的方法?

1 个答案:

答案 0 :(得分:0)

找到了这个解决方案:

public class Person : INotifyPropertyChanged
{
private string _name;
private int? _version;
public event PropertyChangedEventHandler PropertyChanged;
public int? version 
    {
        get { return _version; }
        set { SetField(ref _version, value, "version"); }
    }
public int? id { get; set; }
public string name 
    {
        get { return _name; }
        set { SetField(ref _name, value, "name"); }

    }
public bool? isNeeded { get; set; }

protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

}