简体   繁体   中英

structs and INotifyPropertyChanged

I'm trying to add properties to my Model playing with my first MVVM app. Now I want to add a place to save specific data in a clean way, so I used a struct. But I am having issues to notify property changed, it does not have access to the method (An object reference is required for the non-static field) Can someone explain to me why this happens and inform me on a strategy that fit my needs?

Thanks!

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;

OnPropertyChanged needs to be defined in the scope that you wish to update properties on.

For that to work you'll have to implement the interface INotifyPropertyChanged .

And finally you have to provide the correct argument to the OnPropertyChanged method. 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've got a class sorounding the code you provided in your example.

That means you've nested a struct inside a class. Just because you've nested your struct, doesn't mean it inherits properties and methods from the outer class. You still need to implement INotifyPropertyChanged inside your struct and define the OnPropertyChanged method inside it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM