【问题标题】:Is it possible to fire the OnPropertyChanged Event without explictly calling it in the setter of a property on ViewModel?是否可以触发 OnPropertyChanged 事件而无需在 ViewModel 上的属性设置器中明确调用它?
【发布时间】:2017-04-30 12:06:30
【问题描述】:

在我的场景中,每次更改属性时,我都想触发 OnPropertyChanged 事件

是否可以编写一个自动执行此操作的基本 ViewModel,也许在属性值更改时传递 nameof(property)?

提前致谢。

【问题讨论】:

    标签: c# mvvm xamarin xamarin.forms viewmodel


    【解决方案1】:

    是否可以在不编写代码的情况下触发PropertyChanged 事件? 是的,尽管您必须使用将调用注入称为 Fody 的第 3 方库。您可以在以下位置找到它:https://github.com/Fody/PropertyChanged

    如果你愿意写一个代码,你可以把它放在你的基类中(C#6 代表?。你需要System.Runtime.CompilerServices 代表CallerMemberName):

    protected void OnPropertyChanged([CallerMemberName]string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventargs(propertyName));
    }
    

    所以在你的属性设置器中你只是放了

    set
    {
       backingField = value;
       OnPropertyChanged();
    }
    

    【讨论】:

    • 是什么?在这种情况下怎么办?防止在 PropertyChanged 为空时调用 Invoke?
    • @EstebanVerbel 没错。并且它的线程安全。 ?.Invoke 是使用 C# 6 引发事件的首选方式。更具体地说,?。如果左侧参数为 null,则导致表达式返回 null;这意味着它之后的任何代码都不会执行。
    • 感谢您的澄清。
    【解决方案2】:

    Fody 允许您使用属性来连接 INotifyPropertyChanged,而不必在每个 setter 中显式调用它。

    [ImplementPropertyChanged]
    public class Person 
    {        
        public string GivenNames { get; set; }
        public string FamilyName { get; set; }
    }
    

    【讨论】:

    • 非常感谢您的意见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2022-01-03
    • 2016-07-25
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多