将代码放在依赖项属性的setter块中是安全的,还是应该总是使用回调方法?

LeB*_*nes 3 c# wpf xaml uwp

将代码放在依赖项属性的setter块中是安全的,还是应该总是使用回调方法?有什么不同?

    public static readonly DependencyProperty BodyTextProperty =
        DependencyProperty.Register("BodyText", typeof(string), typeof(EliteEditor), new PropertyMetadata(string.Empty, BodyText_Callback));

    public string BodyText
    {
        get { return (string)GetValue(BodyTextProperty); }
        set 
        { 
            /***** IS IT SAFE TO WRITE CODE HERE? *****/
            SetValue(BodyTextProperty, value); 
        }
    }

    private static void BodyText_Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        /***** OR SHOULD I ALWAYS WRITE CODE HERE? *****/
    }
Run Code Online (Sandbox Code Playgroud)

Bra*_*NET 8

只有在C#中实际调用该setter 时才会触发setter块中的代码(通过BodyText = someValue某处).如果运行时更新依赖项属性(例如通过绑定更新),则不会触发它.

从技术上讲,您甚至不需要定义属性 ; 如果没有它,系统将正常工作.该片段生成它以使您的生活更轻松.

因此,您应始终对回调进行编码; 从来没有在二传手中有逻辑.

  • 我猜*需要*是上下文,但通常人们希望能够在XAML中设置属性,这需要CLR包装器属性. (2认同)