【问题标题】:Binding to dependencyproperty on a per object basis基于每个对象绑定到依赖属性
【发布时间】:2012-08-03 19:12:30
【问题描述】:

我有以下类架构

public Class Test : DependencyObject 
{
    private DependencyProperty _thickness = DependencyProperty.Register("Thickness", typeof(double), typeof(CounterDataStreamWrapper));
    public double Thickness
    {
        get 
        { 
            return (double)GetValue(this._thickness); 
        }
        set
        {
            SetValue(this._thickness, value);
        }
    }


    ... Rest of the code
}

基本上我有一组 Test 对象,我想将每个对象的厚度值绑定到其对应的 UI 元素。我对 C# 绑定不太熟悉。当我尝试创建多个对象时,我遇到了“DependencyProperty 已注册”问题。我确信我只是缺少一些绑定到 DependencyProperty 的关键概念。

感谢任何帮助!

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    您正在 CounterDataStreamWrapper 类型上注册厚度依赖属性,并且每个实例都是私有的。

    将 DependencyProperty 设为公共静态并将其注册到类 Test。

    public static DependencyProperty Thickness = 
        DependencyProperty.Register("Thickness", typeof(double), typeof(Test));
    

    【讨论】:

    • 其实如果是静态的,Test的多个实例怎么会有不同的Thickness值呢?
    • 你应该将静态命名为ThicknessProperty;它是一个标识符,它不是属性本身。 msdn.microsoft.com/en-us/library/ms752914.aspx
    • @Jin 这就是依赖属性的工作方式——注册属性与存储值是分开的。这些值实际上存储在其他地方并与Test的实例相关联
    【解决方案2】:

    它应该是静态的。像这样:

    private static DependencyProperty _thickness ...
    

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 2013-02-10
      • 2016-01-22
      • 1970-01-01
      • 2023-03-26
      • 2018-05-21
      • 2018-09-20
      • 1970-01-01
      • 2012-08-26
      相关资源
      最近更新 更多