【问题标题】:How to use NotifyOfPropertyChange in static property (Caliburn Micro)如何在静态属性中使用 NotifyOfPropertyChange (Caliburn Micro)
【发布时间】:2018-04-20 13:51:51
【问题描述】:
  1. 为什么我不能在静态属性中使用 NotifyOfPropertyChange?
  2. caliburn micro 中是否还有另一个 NotifyOfPropertyChange 函数可用于静态属性或其他使用方式以及如何使用?

    private static string _data = "";
    
    public static string _Data
    {
        get
        {
            return _data;
        }
        set
        {
            _data = value;
            NotifyOfPropertyChange(() => _Data);          
        }
    }
    

【问题讨论】:

    标签: c# wpf mvvm caliburn.micro


    【解决方案1】:

    您可以创建自己的方法来引发StaticPropertyChanged 事件:

    private static string _data = "";
    public static string _Data
    {
        get
        {
            return _data;
        }
        set
        {
            _data = value;
            NotifyStaticPropertyChanged(nameof(_Data));
        }
    }
    
    
    
    public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
    private static void NotifyStaticPropertyChanged(string propertyName)
    {
        if (StaticPropertyChanged != null)
            StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
    }
    

    更多信息请参考以下博文:http://10rem.net/blog/2011/11/29/wpf-45-binding-and-change-notification-for-static-properties

    【讨论】:

    【解决方案2】:

    为什么我不能在静态属性中使用 NotifyOfPropertyChange?

    好吧,你不能像现在这样使用它,因为NotifyOfPropertyChange 是一个实例方法,而不是静态方法。

    caliburn micro [...] 中是否还有另一个 NotifyOfPropertyChange 函数?

    不,据我所知,它不是。但是,您可以推出自己的实现,例如

    public static event PropertyChangedEventHandler PropertyChanged;
    
    private static void NotifyPropertyChange<T>(Expression<Func<T>> property)
    {
        string propertyName = (((MemberExpression) property.Body).Member as PropertyInfo).Name;
        PropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
    }
    

    然后可以这样调用

    NotifyOfPropertyChange(() => _Data);
    

    在你的属性设置器中。


    关于签名的编辑:

    代替

    private static void NotifyPropertyChange<T>(Expression<Func<T>> property) { ... }
    

    你也可以使用

    private static void NotifyPropertyChange([CallerMemberName] string property) { ... }
    

    它的好处是你不必显式传递任何东西,你可以像这样调用它

    NotifyPropertyChange();
    

    因为编译器会自动inject属性名。

    我只选择了Expression&lt;Func&lt;T&gt;&gt;,因为这个电话(几乎)与对 caliburn micro 的NotifyPropertyChange 的电话完全相同。


    您需要知道的是,由于NotifyPropertyChange 方法是静态方法而不是实例方法,您不能将其重构为基类(例如MyViewModelBase)就像您可以使用实例方法一样 - 这也是 caliburn micro 所做的。

    因此,您需要在每个具有静态属性的 ViewModel 中复制并粘贴事件和 NotifyPropertyChange&lt;T&gt; 方法,或者创建一个封装功能的静态助手。

    【讨论】:

    • 太棒了!有很大帮助:) 谢谢
    • @FrancisCanoza 很高兴听到它有帮助。另请参阅我对NotifyPropertyChange 方法的签名所做的编辑。您可以使用任何您想使用的签名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多