在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的选择呢?
(注意:在我的特定情况下,我需要它用于TextBox
和ComboBox
)
找到了模糊的比赛。
…如果有多个重载且没有指定类型签名,则GetMethod
通常抛出…(MSDN: More than one method is found with the specified name.
)。 基本上WPF引擎只是在寻找一种这样的方法。
为什么不检查方法体中的类型并在不允许的情况下抛出InvalidOperationException
?
但请注意,那些CLR-Wrappers不应该包含设置和获取旁边的任何代码 ,如果在XAML中设置了它们将被忽略 ,尝试在setter中抛出exception,如果你只使用XAML来设置它就不会出现价值。
改为使用回调:
上述就是C#学习教程:在wpf中限制附加的依赖属性分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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."); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/951013.html