如何在基类中使用static propertychanged?

时间:2017-10-20 17:43:31

标签: c# wpf mvvm

我的课程中有一些属性并使用MVVM。程序中的每个ViewModel类都继承一个名为ObservableObject的类,它实现了INotifyPropertyChanged。因此,当ViewModel继承ObservableObject时,我不会重写相同的代码。但是,我有一些静态属性。 ObservableObject中的静态事件始终为NULL,但在派生类(ViewModel)中发布代码时正常工作。那是怎么发生的?为什么我的静态属性更改事件在它是基类时始终为空?如果我真的想在基类中编写,我该怎么办?

这是我的代码:

ObservableObject

public abstract class ObservableObject : INotifyPropertyChanged
    {
        //I don't post Non-static version, it work normally.

        //Here is the static version, if I post the code below in the MainViewModel, everything works fine.  

        public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;

        protected static void OnStaticPropertyChanged([CallerMemberName]string info = "")
        {
            if (StaticPropertyChanged != null)
            {
                StaticPropertyChanged(null, new PropertyChangedEventArgs(info));
            }
        }

        protected static bool SetStaticValue<T>(ref T oldValue, T newValue, [CallerMemberName]string propertyName = "")
        {
            if (object.Equals(oldValue, newValue))
            {
                return false;
            }
            oldValue = newValue;
            OnStaticPropertyChanged(propertyName);
            return true;
        }

    }



//I change value of TabIndex by clicking a button, but there is no change 
//I bind the property in the XAML
public class MainViewModel: ObservableObject
{
    private int _tabIndex;
    public MainViewModel()
    {           
      TabIndex = 0; //There is no change on the window
    }

    public static int TabIndex
    {
        get { return _tabIndex; }
        set
        {
            SetStaticValue(ref _tabIndex, value);
        }
    }
}

0 个答案:

没有答案