繁体   English   中英

结构和INotifyPropertyChanged

[英]structs and INotifyPropertyChanged

我正在尝试通过第一个MVVM应用程序向模型添加属性。 现在,我想添加一个位置以干净的方式保存特定数据,因此我使用了一个结构。 但是我在通知属性更改时遇到问题,它无法访问该方法(非静态字段需要对象引用)有人可以向我解释为什么会发生这种情况,并告知我适合我需要的策略吗?

谢谢!

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

为此,您必须实现INotifyPropertyChanged接口。

最后,您必须为OnPropertyChanged方法提供正确的参数。 在此示例中,“已停止”

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;
}

编辑:在您的评论中您提到您有一个围绕示例中提供的代码的类。

这意味着您已经在一个类中嵌套了一个结构。 仅仅因为您嵌套了struct,并不意味着它从外部类继承了属性和方法。 您仍然需要在结构内部实现INotifyPropertyChanged并在其中定义OnPropertyChanged方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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