ord*_*dag 11 .net c# wpf dependency-properties
我想仅将依赖属性附加到特定控件.
如果只是一种类型,我可以这样做:
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);
}
Run Code Online (Sandbox Code Playgroud)
(所以:限制ControlGet/Set-Methods中的类型)
但是现在我想允许该属性附加在不同类型的属性上Control.
您尝试使用该新类型为这两个方法添加重载,但由于"未知的构建错误,找到了模糊匹配"而无法编译.
那么如何限制我DependencyProperty选择Controls呢?
(注意:在我的具体情况下,我需要它TextBox和ComboBox)
找到了模棱两可的比赛.
...通常是通过抛出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.");
}
}
Run Code Online (Sandbox Code Playgroud)