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
)
Ambiguous match found.
...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:
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.");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.