2

INotifyPropertyChanged在自定义类中使用了在变量更改时触发事件,但我想知道是否有一种简单的方法可以在单个变量更改时触发事件,例如双精度。

例如,在 WPF 应用程序中,如果我有

private double a;

MainWindow.xaml.cs,是否有一种简单的方法可以在任何时间触发事件a

4

4 回答 4

3

字段没有任何跟踪更改的方法。为了使它工作,它需要是一个属性,并且需要一些东西来处理跟踪。这就是INotifyPropertyChanged接口的目的。

跟踪此值更改的正常方法是INotifyPropertyChanged在您的类中实现。

于 2013-06-12T23:10:49.057 回答
2

如果我理解正确,您需要为 a 创建一个 Setter,然后触发 propertyychange 事件/自定义事件,而不是封装a到一个类中。

像这样的东西:

private double a;

    public double A
    {
        get { return a; }
        set { a = value;
              firepropertyChange(a);
            }
    }
于 2013-06-12T23:13:30.600 回答
0

If you are using C# 5.0, you can employ CallerMemberName attribute this way:

class MyData : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged();
        }
    }

    private string _anotherProperty;
    public string AnotherProperty
    {
        get { return _anotherProperty; }
        set
        {
            _anotherProperty = value;
            RaisePropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged([CallerMemberName] string caller = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(caller));
        }
    }
}

As you see you just have to call RaisePropertyChanged(); in set for each property, without typing the property names over and over.

Another approach would be to define a ModelBase class:

class ModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void Set<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
    {
        if (!Object.Equals(field, value))
        {
            field = value;

            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

And then derive your model from ModelBase:

class Conf : ModelBase
{
    NodeType _nodeType = NodeType.Type1;

    public NodeType NodeType
    {
        get { return _nodeType; }
        set { Set(ref _nodeType, value); }
    }
}
于 2013-06-12T23:42:02.047 回答
0

的(取决于),如果您通过属性包装变量访问并在更改时触发事件,并确保对该变量的所有访问都是通过该属性进行的,例如

private double a;

public double PropertyA
{
    get
    {
        return a;
    }
    set
    {
        // set value and fire event only when value is changed
        // if we want to know when value set is the same then remove if condition
        if (a != value)
        {
            a = value;
            PropertyChanged("PropertyA");
        }
    }
}

// when changing a, make sure to use the property instead...
PropertyA = 5.2;

...否则,不

于 2013-06-12T23:14:36.347 回答