当 PropertyChangedEventHandler 完成这项工作时,设置依赖属性有什么意义呢?

发布于 2024-08-04 05:55:30 字数 691 浏览 3 评论 0原文

目前,我已经使用以下方法对我在 xaml 中绑定的任何属性设置更改通知:

    class MyClass : INotifyPropertyChanged
{
    string name;

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NotifyPropertyChanged("Name");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

但是,我已经看到要实现依赖项属性,我需要做一些事情,例如注册它和设置回调等,其中转最终只会调用上面的代码。

那么,当我可以使用上述方法时,为依赖属性设置所有额外的样板内容有什么意义呢?

谢谢。

Currently I have use the following approach to setup change notification on any of my properties that I bind to in xaml:

    class MyClass : INotifyPropertyChanged
{
    string name;

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NotifyPropertyChanged("Name");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

However, I've seen that to implement a dependency property I need to do stuff like registering it and setting callbacks etc, which in turn will just end up calling the above code.

So what's the point of setting all the extra boiler plate stuff for dependency properties when I can just use the above approach?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

殊姿 2024-08-11 05:55:30

依赖属性可以是绑定的目标,而常规 CLR 属性则不能。这就是为什么控件(绑定目标)的属性通常是依赖属性,而模型或 ViewModel 类(绑定源)的属性则不是。

Dependency properties can be the target of a binding, whereas regular CLR properties can't. That's why the properties of a control (binding target) are usually dependency properties, whereas the properties of a model or ViewModel class (binding source) are not.

葮薆情 2024-08-11 05:55:30

您所做的事情是正确的(假设我理解正确)依赖属性不适用于您在模型中绑定的内容,它们适用于模型将绑定到的控件中的属性 - 例如文本框中的 Text 属性。

在自定义控件中使用它们有很多原因,其中最重要的是它们附带的自动管道,以便它们能够正确绑定到示例中声明的属性。

What you are doing is correct (assuming I understand it correctly) dependency properties are not for the things you bind to in the model they are for the properties in controls that the model will be bound to - for example the Text property in a text box.

There are a number of reasons to use them in your custom controls, not least of which is the automatic plumbing that comes with them so that they will correctly bind to a property declared as in your example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文