限制 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
?
(注意:在我的具体情况下,我需要它用于 TextBox
和 ComboBox
)
I want to attach a dependency property to specific controls only.
If that is just one type, I can do this:
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);
}
(So: limit the Control
type in the Get/Set-Methods)
But now I want to allow that property to get attached on a different type of Control
, too.
You'd try to add an overload for both methods with that new type, but that fails to compile because of an "Unknown build error, Ambiguous match found."
So how can I limit my DependencyProperty
to a selection of Control
s?
(Note: In my specific case I need it for TextBox
and ComboBox
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
...通常由
GetMethod
抛出如果存在多个重载并且未指定类型签名(MSDN:发现具有指定名称的多个方法。
)。基本上,WPF 引擎只是寻找一种这样的方法。为什么不检查方法主体中的类型并在不允许的情况下抛出
InvalidOperationException
?但请注意,除了设置和获取之外,这些 CLR 包装器不应包含任何代码,如果在 XAML 中设置属性它们将被忽略,请尝试在setter,如果只使用XAML设置值,则不会出现。
使用回调代替:
...is normally thrown by
GetMethod
if there are multiple overloads and no type-signature has been specified (MSDN:More than one method is found with the specified name.
). Basically the WPF-engine is only looking for one such method.Why not check the type in the method body and throw an
InvalidOperationException
if it's not allowed?Note however that those CLR-Wrappers should not include any code beside the setting and getting, if the propery is set in XAML they will be disregarded, try throwing an exception in the setter, it will not come up if you only use XAML to set the value.
Use a callback instead: