使用绑定依赖属性XAML

时间:2017-03-24 16:32:51

标签: c# wpf xaml

为另一个依赖属性问题道歉

以下问题:

XAML Binding on Dependency Property

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

和本教程:

http://wpftutorial.net/DependencyProperties.html

我遇到了类似的问题。在尝试解决方案后,没有太大的变化。

我制作了一个控制库:WpfCustomControlLibrary1

 public class CustomControl1 : Control
{



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

并添加了一个带有所需回调的依赖项属性:

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;

        }
    }

}
}

然后我尝试将属性设置为应用程序中的绑定,但是出现错误说:

error

如何将我的dependancy属性设置为依赖对象?或者是他们设置绑定到依赖属性的方法吗?

并非依赖项属性的基类是依赖项对象吗?

1 个答案:

答案 0 :(得分:3)

使用正确的名称注册DP:

DependencyProperty.Register("Dictionary", ...

然后在DP包装器属性中使用GetValueSetValue方法

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

private Dictionary<string, int> _Dictionary;字段不是必需的