【问题标题】:Using bindings for dependency property XAML使用依赖属性 XAML 的绑定
【发布时间】:2023-03-13 07:27:01
【问题描述】:

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

以下问题:

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;

        }
    }

}
}

然后我尝试将属性设置为应用程序中的绑定,但收到错误消息:

如何将我的依赖属性设置为依赖对象?还是他们设置绑定到依赖属性的一种方式?

依赖属性的基类不是依赖对象吗?

【问题讨论】:

  • 当你注册一个依赖属性时,你应该注册你想使用的名字"Dictionary"而不是"DictionaryProperty"。如果您使用的是 Visual Studio,您可能有权访问内置的 sn-p。在代码中输入propdp 并点击两次tab。
  • 请解释否决票

标签: c# wpf xaml


【解决方案1】:

用正确的名字注册 DP:

DependencyProperty.Register("Dictionary", ...

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

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

private Dictionary&lt;string, int&gt; _Dictionary; 字段不是必需的

【讨论】:

    猜你喜欢
    • 2014-01-09
    • 2011-06-25
    • 2017-03-04
    • 2017-12-18
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    相关资源
    最近更新 更多