在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中抛出exception,如果你只使用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."); } }