Structs and INotifyPropertyChanged

I am trying to add properties to my model with my first MVVM application. Now I want to add a place to store specific data in a clean way, so I used a structure. But I am having problems with property change notification, it does not have access to the method (object reference is required for non-static field) Can someone explain to me why this is happening and advise me on a strategy that suits my needs?

Thank!

public ObservableCollection<UserControl> TimerBars
{
    get { return _TimerBars; }
    set
    {
        _TimerBars = value;
        OnPropertyChanged("TimerBars");
    }
}

public struct FBarWidth
{
    private int _Stopped;
    public int Stopped
    {
        get { return _Stopped; }
        set
        {
            _Stopped = value;
            OnPropertyChanged("Name"); //ERROR: An object reference is required for the non-static field
        }
    }

    private int _Running;
    //And more variables
}


private void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
public event PropertyChangedEventHandler PropertyChanged;

      

-2


source to share


1 answer


OnPropertyChanged

must be defined in the scope where you want to update the properties.

To do this, you will need to implement an interface INotifyPropertyChanged

.

Finally, you must provide the correct argument to the method OnPropertyChanged

. In this example, "Stopped"



public struct FBarWidth : INotifyPropertyChanged
{
    private int _Stopped;
    public int Stopped
    {
        get { return _Stopped; }
        set
        {
            _Stopped = value;
            OnPropertyChanged("Stopped");
        }
    }

    private int _Running;
    //And more variables

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

      

Edit: In your comment, you mentioned that you have a compromising class of code that you provided in your example.

This means that you have nested the structure inside the class. Just because you nested your struct doesn't mean that it inherits properties and methods from the outer class. You still need to implement INotifyPropertyChanged

inside your structure and define a method inside it OnPropertyChanged

.

+1


source







All Articles