簡體   English   中英

WPF附加屬性和綁定的奇怪行為

[英]Strange behavior for WPF attached property and binding

我試圖在網格控件上注冊WPF附加屬性,但是,今天我遇到了非常奇怪的行為:

public static class MyClass
{
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(string),
        typeof(MyClass), null);

    public static string GetMyProperty(DependencyObject d)
    {
        return (string)d.GetValue(MyPropertyProperty);
    }

    public static void SetMyProperty(DependencyObject d, string value)
    {
        d.SetValue(MyPropertyProperty, value); //<-- set breakpoint here
    }
}

XAML:

<GridControl local:MyClass.MyProperty="My Name">
...
</GridControl>

當我這樣寫時,附加屬性的setter永遠不會執行。 和價值永遠不會被設定。 但我可以窺探到網格,並發現附上的屬性附加了一個空值。

但是當我將附加的屬性名稱更改為:

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("xxxMyProperty", typeof(string),
        typeof(MyClass), null);

即使用不同於MyProperty的名稱。 然后可以擊中斷點! 和值可以設置!

此外,當我將附加屬性更改為:

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(string),
        typeof(UIElement), null);

即將所有者類型更改為UIElement,然后我也可以點擊斷點,只是想知道為什么?

但是,當我在XAML中設置綁定而不是字符串常量時,上述每種情況都會出現一個異常,說明A 'Binding' can only be set on a DependencyProperty of a DependencyObject

綁定XAML示例:

<GridControl local:MyClass.MyProperty="{Binding MyStringValue}">
...
</GridControl>

有人遇到過這種奇怪的行為嗎? 我的情況下我想念什么? 預先感謝您的答復!

如果您將SetMyProperty方法稱為“設置者”,那么您應該知道這些方法只是供您使用的“幫助”方法。 該框架通常不使用這些方法。

但是,如果您說您想知道值何時更改,那么還有另一種方法。 PropertyChangedCallback處理程序添加到PropertyChangedCallback的聲明中:

public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.RegisterAttached("MyProperty", typeof(string), typeof(MyClass), 
    new UIPropertyMetadata(default(string.Empty), OnMyPropertyChanged));

public static void OnMyPropertyChanged(DependencyObject dependencyObject, 
    DependencyPropertyChangedEventArgs e)
{
    string myPropertyValue = e.NewValue as string;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM