简体   繁体   English

C#依赖项属性-是否在CLR包装器中检查值

[英]C# Dependency Properties - Whether to Check Value in CLR Wrapper

On writing custom dependency proerties in C#, a fairly common wrapper goes something like: 在用C#编写自定义依赖项属性时,一个相当普通的包装器如下所示:

    public string Surname
    {
        get
        {
            return this.GetValue(SurnameProperty) as string;
        }

        set
        {
            this.SetValue(SurnameProperty, value);
        }
    }

Now, when using the NotifyPropertyChanged system, I would normally check whether a value has changed in the 'set' block before actually committing the value and calling OnPropertyChanged. 现在,当使用NotifyPropertyChanged系统时,我通常会在实际提交值并调用OnPropertyChanged之前检查“设置”块中的值是否已更改。 Should I do the same for dependency properties? 我应该对依赖属性做同样的事情吗? ie: 即:

        set
        {
            if(this.GetValue(SurnameProperty) != value)
               this.SetValue(SurnameProperty, value);
        }

...or is this something that is completely unnecessary and already taken care of by the CLR? ...或者这是完全不必要的并且已经由CLR处理了吗? All examples on MSDN that I have seen to not bother to do any checking before calling SetValue. 我已经看到在MSDN上的所有示例,在调用SetValue之前不必费心进行任何检查。 Many thanks. 非常感谢。

The short answer is, no it's taken care by the framework already. 简短的答案是,不,它已经被框架照顾了。

Actually, according to Adam Nathan's "Windows Presentation Foundation", XAML compiler depends on the property warpper at compile time. 实际上,根据Adam Nathan的“ Windows Presentation Foundation”,XAML编译器依赖于编译时的属性warpper。 However, .NET property wrappers are actually bypassed at run-time in XAML. 但是,.NET属性包装器实际上是在XAML运行时绕过的。 Therefore, you should actually avoid adding any kinds of logic in addtion to GetValue/SetValue. 因此,实际上应该避免在GetValue / SetValue之外添加任何逻辑。 Whatever logic you added in the setter is only executed if you call the property explicitly. 仅当您显式调用属性时,才执行在setter中添加的任何逻辑。 However, if you bind that property in XAML, the runtime will skip it. 但是,如果在XAML中绑定该属性,则运行时将跳过该属性。 If you have a bug in your setter, this may take you some time to figure out. 如果安装程序中有错误,则可能需要一些时间才能解决。 Please see page 53 if you got that book in your hand. 如果您手里拿着那本书,请参阅第53页。

不,它由依赖项属性系统处理。

It is taken care by the property changed callback. 属性更改回调很小心。 The PropertyChangedCallback is called only when there is a change in the property value. 仅当属性值发生更改时,才调用PropertyChangedCallback

public static readonly DependencyProperty MyDependencyProperty =
                   DependencyProperty.Register(
                         "Dependency",
                          typeof(string),
                          typeof(MyUserControl),
                          new FrameworkPropertyMetadata("Initializing...", new PropertyChangedCallback(OnMyDependencyChangedCallBack)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM