简体   繁体   中英

Using bindings for dependency property XAML

Apologies for yet another Dependency property question

Following these questions:

XAML Binding on Dependency Property

A 'Binding' can only be set on a DependencyProperty of a DependencyObject

and this tutorial:

http://wpftutorial.net/DependencyProperties.html

I am having a similar problem. and after trying the solutions not much has changed.

I have made a control library: WpfCustomControlLibrary1

 public class CustomControl1 : Control
{



    static CustomControl1()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
    }

And added a dependency property with the required callbacks:

FrameworkPropertyMetadata meta = new FrameworkPropertyMetadata(null,FrameworkPropertyMetadataOptions.Inherits, PropertyChangedCallbackMethod, OnDictionaryCoerce,false);

    public static readonly DependencyProperty DictionaryProperty = DependencyProperty.Register("DictionaryProperty",typeof(Dictionary<string,int>),
        typeof(CustomControl1),new FrameworkPropertyMetadata(null,FrameworkPropertyMetadataOptions.Inherits));

    private Dictionary<string, int> _Dictionary;

    public static void PropertyChangedCallbackMethod(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // I am not entirely sure what code should be implemented here, leaving it blank for now
    }

    private static Object OnDictionaryCoerce(DependencyObject sender,Object data)
    {
        return data;
    }

    private static bool OnValidate(object data)
    {
        return data is Dictionary<string, int>;
    }
    public Dictionary<string, int> Dictionary
    {
        get
        {
            return _Dictionary;
        }
        set
        {
            _Dictionary = value;

        }
    }

}
}

I then try to set the property to a binding in an application but am given an error saying:

错误

How do I set my dependancy property to be a dependancy object? or is their a way to set a binding to a dependency property?

And isn't the base class of a dependency property a dependency object?

Register DP with correct name:

DependencyProperty.Register("Dictionary", ...

and then in DP wrapper property use GetValue , SetValue methods

public Dictionary<string, int> Dictionary
{
    get
    {
        return (Dictionary<string, int>)GetValue(DictionaryProperty);
    }
    set
    {
        SetValue(DictionaryProperty, value);
    }
}

private Dictionary<string, int> _Dictionary; field is not necessary

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM