【发布时间】: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