Fire event when changing the value of double

I used INotifyPropertyChangedin a custom class to fire an event when a variable changed, but I was wondering if there is an easy way to fire an event when a single variable changes, for example, in double.

For example, in a WPF application, if I have

private double a;

Q MainWindow.xaml.cs, is there an easy way to fire an event at any time afor?

+2
source share
4 answers

If you understand correctly, you need to create a Setter for a, which then fires the event / custom eventy event, rather than encapsulating it ain a class.

Something like that:

private double a;

    public double A
    {
        get { return a; }
        set { a = value;
              firepropertyChange(a);
            }
    }
+2

. , , - . INotifyPropertyChanged.

INotifyPropertyChanged .

+3

(), , , ,

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;

... no

0

# 5.0, CallerMemberName :

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 can see, you just need to call RaisePropertyChanged();in setfor each property without typing property names again and again.

Another approach would be to define a class ModelBase:

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); }
    }
}
0
source

Source: https://habr.com/ru/post/1625832/


All Articles