c# - 了解 PropertyChanged 机制的工作原理(工作流程)

标签 c# events

说明: 1.- 我不知道这是否有一个特定的名称或单词在英语或编程俚语中引用它,所以这可能是一个重复的帖子,因为我无法查看

2.- 我对这些东西完全是新手,我从未使用过处理程序,所以这是问题的一部分。

我正在尝试了解NotifyPropertyChanged 机制的工作原理。基于:INotifyPropertyChanged ,着重于示例。 (我看的是西类牙文的,上面你可以把它改成原来的英文,如果它不会自动改变。

下面我就把让我疑惑的主要代码摘下来,试着分析一下。希望你能告诉我哪里(如果存在)我错了以及我不明白的地方。 让我们关注实现接口(interface)的类

// This is a simple customer class that 
// implements the IPropertyChange interface.
public class DemoCustomer : INotifyPropertyChanged
{
    // These fields hold the values for the public properties.
    private Guid idValue = Guid.NewGuid();
    private string customerNameValue = String.Empty;
    private string phoneNumberValue = String.Empty;

    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    // The constructor is private to enforce the factory pattern.
    private DemoCustomer()
    {
        customerNameValue = "Customer";
        phoneNumberValue = "(312)555-0100";
    }

    // This is the public factory method.
    public static DemoCustomer CreateNewCustomer()
    {
        return new DemoCustomer();
    }

    // This property represents an ID, suitable
    // for use as a primary key in a database.
    public Guid ID
    {
        get
        {
            return this.idValue;
        }
    }

    public string CustomerName
    {
        get
        {
            return this.customerNameValue;
        }

        set
        {
            if (value != this.customerNameValue)
            {
                this.customerNameValue = value;
                NotifyPropertyChanged();
            }
        }
    }

    public string PhoneNumber
    {
        get
        {
            return this.phoneNumberValue;
        }

        set
        {
            if (value != this.phoneNumberValue)
            {
                this.phoneNumberValue = value;
                NotifyPropertyChanged();
            }
        }
    }

嗯,我明白什么? (或者相信它)。

来自:

public event PropertyChangedEventHandler PropertyChanged;

1.- PropertyChanged 是一种方法。将在 ProperyChanged 事件 触发时执行的事件。

疑惑:但是这个方法从来没有实现过...

来自:

private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

2.- NotifyPropertyChanged 是一种方法。由我们创建,可以有我们想要的任何名称。此方法将在属性被修改时由我们启动。

问题:此方法会触发ProperyChanged 事件吗?

疑问:对我来说,正如我在那里看到的那样,没有人启动此事件,但我们创建的方法在触发时启动。但是因为它不触发,我们直接启动方法而不是它......

Mixture 最终认为:NotifyPropertyChanged 使用 Hanlder 抛出事件,以便被“上级实体”(示例代码中的绑定(bind)源)捕获,后者接收修改后的属性以便更新它。那么,如果我想知道哪些元素/类可以感知这种事件,我该怎么办?

我认为最后一个是正确的,但由于我不是专家,而是我在尝试理解它和写这个问题时的想法,我希望你能纠正我。

非常感谢!

已更新

非常感谢大家!那么,我可以用我想要的方法订阅事件吗?我试过:

objetos[usados] = new ItemDB();
objetos[usados].PropertyChanged += mensaje();

与:

public async void mensaje(string cadena)
{
    var dlg = new ContentDialog(){
        Title = "My App",
        Content = cadena,
        PrimaryButtonText = "Yes",
        SecondaryButtonText = "No"
    };

    var result = await dlg.ShowAsync();

}

然后 VS 说:

Error 1 Ninguna sobrecarga correspondiente a 'mensaje' coincide con el 'System.ComponentModel.PropertyChangedEventHandler' delegado

翻译:

Error 1 No one overload corresponding to 'mensaje' matches with 'System.ComponentModel.PropertyChangedEventHandler' delegate

为什么它不起作用,因为我的事件是用一个字符串 arg 给出的,而 mensaje 接收作为参数和字符串?

最佳答案

我建议您查看 C# 中的 EventsDelegates 以进一步阅读。

public event PropertyChangedEventHandler PropertyChanged;

PropertyChanged 是一个 EventHandler,它是一个委托(delegate)。其他代码可以在此处注册并在调用委托(delegate)时执行。

那么 INotifyPropertyChanged 会发生什么:

一些代码(可能是 Xaml 中的绑定(bind))注册了 PropertyChanged 事件:

yourobject.PropertyChanged += MethodThatShouldBeCalledWhenThePropertyChanges;

(这是在某处自动生成的最合适的方法,因为它是从 xaml 生成的,但您也可以通过这种方式手动生成。)

NotifyPropertyChanged 方法中,事件委托(delegate)被执行。 它只是执行添加到事件中的所有方法。

所以回答你的问题:

是的,NotifyPropertyChanged 中的代码“触发”了该事件。它调用添加到事件中的每个方法。

任何代码都可以注册事件。

截至您的更新:

我再次建议阅读委托(delegate)。

您可以将委托(delegate)视为方法接口(interface)。它定义了一个方法必须采用特定的参数类型来匹配委托(delegate)。

PropertyChanged 的​​类型为 PropertyChangedEventHandler它采用一个对象和一个 PropertyChangedEventArgs 参数。

所以像这样的任何方法都是合适的:

void MethodName(
Object sender,
PropertyChangedEventArgs e
)

关于c# - 了解 PropertyChanged 机制的工作原理(工作流程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28043183/

相关文章:

events - 服务级别的Grails域类事件监听器

java - 观察者模式混淆

Javascript添加监听器错误: TypeError: trigger. addEventListener不是函数

c# - Xamarin ResolveLibraryProjectImports 任务失败

c# - ASP.NET 5/MVC 6 控制台托管应用程序

events - 分布式系统: Keeping timestamp consistency between different nodes

swift - NSEvent.keyCode 到 Swift 中的 unicode 字符

c# - 如何从 C# 中的 URL 查询字符串中提取值?

c# - 我的 DLL 有 4 个副本而不是 1 个?

c# - 有一个空的属性类不好吗?