Limit attached dependency property in wpf

蓝咒 提交于 2019-12-06 19:29:57

问题


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 Controls?
(Note: In my specific case I need it for TextBox and ComboBox)


回答1:


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


来源:https://stackoverflow.com/questions/6874427/limit-attached-dependency-property-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!