开发者

Limit attached dependency property in wpf

开发者 https://www.devze.com 2023-03-23 16:05 出处:网络
I want to attach a dependency property to specific controls only. If that is just one type, I can do this:

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 a开发者_开发问答n 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 Controls?

(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.");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消