【发布时间】:2011-07-10 20:51:33
【问题描述】:
我有一个自己的依赖属性 Target.Height 使用 BindingOperations.SetBinding() 绑定到普通属性 Source.Height。更新Target.Height 属性应该更新Source.Height 属性。但不是使用依赖属性的实际值,而是使用依赖属性的默认值。这是预期的行为吗?
感谢您的任何提示。我使用的代码:
public class Source
{
private int m_height;
public int Height
{
get { return m_height; }
set { m_height = value; }
}
}
public class Target : DependencyObject
{
public static readonly DependencyProperty HeightProperty;
static Target()
{
Target.HeightProperty =
DependencyProperty.Register("Height", typeof(int), typeof(Target),
new PropertyMetadata(666)); //the default value
}
public int Height
{
get { return (int)GetValue(Target.HeightProperty); }
set { SetValue(Target.HeightProperty, value); }
}
}
Source source = new Source();
Target target = new Target();
target.Height = 100;
Binding heightBinding = new Binding("Height");
heightBinding.Source = source;
heightBinding.Mode = BindingMode.OneWayToSource;
BindingOperations.SetBinding(target, Target.HeightProperty, heightBinding);
//target.Height and source.Height is now 666 instead of 100 ....
【问题讨论】:
-
这绝对是一种奇怪的行为。我能够在 LINQpad 中重现它。我希望值是 100,而不是 666。期待看到答案。
-
复制粘贴和调试你的源代码,这两个属性在你最后一行代码之后,都是666...奇怪...
标签: wpf data-binding c#-3.0 dependency-properties