【问题标题】:Why my System.Windows.Data.Binding fails with a DependencyProperty?为什么我的 System.Windows.Data.Binding 因 DependencyProperty 而失败?
【发布时间】:2011-11-25 08:47:12
【问题描述】:

我的对象得到了以下代码(短版):

public class PluginClass
{
    public int MyInt
    {
        get;
        set;
    }

    public PluginClass()
    {
        Random random = new Random();
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += (sender, e) =>
        {
            MyInt = random.Next(0, 100);
        }
    }
}

然后,我将创建另一个具有 int 作为 DependencyProperty 的类。这是代码(也是简化版)

public class MyClass : FrameworkElement
{
    public int Value
    {
        get
        {
            return GetValue(ValueProperty);
        }
        set
        {
            SetValue(ValueProperty, value);
        }
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(int), typeof(MyClass ), new PropertyMetadata(0));

    public MyClass(object source, string propertyName)
    {
        var b = new System.Windows.Data.Binding();
        b.Source = source;
        b.Path = new PropertyPath(propertyName);
        b.Mode = System.Windows.Data.BindingMode.TwoWay;

        SetBinding(ValueProperty, b);
    }
}

最后我正在创建一个 PluginClass 的实例,我想将我的“MyInt”值绑定到 MyClass 的 int。这是我得到的(简化版)

PluginClass pc = new PluginClass();
MyClass mc = new MyClass(pc, "MyInt");

没有编译问题但是绑定无效。 总而言之,我不知道理论上我是否必须得到:

binding.Source = PluginClass.MyInt;
binding.Path = new PropertyPath("???"); // don't know what to "ask"

binding.Source = PluginClass;
binding.Path = new PropertyPath("MyInt");

我认为第二种方法很好,但我不知道为什么它不起作用:( 任何帮助将不胜感激!

【问题讨论】:

    标签: c# data-binding dependency-properties


    【解决方案1】:

    您的PluginClass 应该实现INotifyPropertyChanged。目前,绑定不知道MyInt 的值已更改。

    实现 INPC 将允许您的类在值更改时通知绑定(您必须在 MyInt 的 set 函数中引发 PropertyChanged)。

    【讨论】:

    • 我正在考虑它,但我得出的结论是它是别的东西!会试一试:)
    猜你喜欢
    • 2012-04-06
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 2013-09-24
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多