为什么我的System.Windows.Data.Binding因为一个DependencyProperty而失败
本文关键字:一个 DependencyProperty 失败 System 我的 Windows Data 因为 Binding 为什么 | 更新日期: 2023-09-27 18:15:47
我得到了以下代码为我的对象(简短版本):
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);
}
}
最后,我创建了一个plugclass的实例,我想将我的"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");
我认为第二种方法是好的,但我不知道为什么它不起作用。
您的PluginClass
应该实现INotifyPropertyChanged。目前,绑定不知道MyInt
的值已经改变。
实现INPC将允许您的类在值发生变化时通知绑定(您必须在MyInt
的set函数中提高PropertyChanged
)。