簡體   English   中英

在wpf中限制附加的依賴項屬性

[英]Limit attached dependency property in wpf

我想僅將依賴屬性附加到特定控件。

如果只是一種類型,我可以這樣做:

public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.RegisterAttached("MyProperty", typeof(object), typeof(ThisStaticWrapperClass));

public static object GetMyProperty(MyControl control)
{
    if (control == null) { throw new ArgumentNullException("control"); }

    return control.GetValue(MyPropertyProperty);
}

public static void SetMyProperty(MyControl control, object value)
{
    if (control == null) { throw new ArgumentNullException("control"); }

    control.SetValue(MyPropertyProperty, value);
}

(所以:限制Get / Set-Methods中的Control類型)

但現在我想允許該屬性附加在不同類型的Control
您嘗試使用該新類型為這兩個方法添加重載,但由於“未知的構建錯誤,找到了模糊匹配”而無法編譯

那么如何將DependencyProperty限制為Control s的選擇呢?
(注意:在我的特定情況下,我需要它用於TextBoxComboBox

找到了模棱兩可的比賽。

....如果有多個重載且沒有指定類型簽名,則GetMethod通常拋出...(MSDN: More than one method is found with the specified name. )。 基本上WPF引擎只尋找一種這樣的方法。

為什么不檢查方法體中的類型,如果不允許,則拋出InvalidOperationException


但請注意,那些CLR-Wrappers不應該包含設置和獲取之外的任何代碼 ,如果在XAML中設置了它們將被忽略 ,嘗試在setter中拋出異常,如果你只使用XAML來設置它就不會出現價值。

改為使用回調:

public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.RegisterAttached
        (
            "MyProperty",
            typeof(object),
            typeof(ThisStaticWrapperClass),
            new UIPropertyMetadata(null, MyPropertyChanged) // <- This
        );

public static void MyPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
    if (o is TextBox == false && o is ComboBox == false)
    {
        throw new InvalidOperationException("This property may only be set on TextBoxes and ComboBoxes.");
    }
}

暫無
暫無

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

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