我有这样的WPF绑定代码:
TestModel source = new TestModel();
TestModel target = new TestModel();
Bind(source, target, BindingMode.OneWay);
source.Attribute = "1";
AssertAreEqual(target.Attribute, "1");
target.Attribute = "foo";
source.Attribute = "2";
AssertAreEqual(target.Attribute, "2");
Run Code Online (Sandbox Code Playgroud)
第二个断言失败了!这对我来说似乎很奇怪.
此外,我尝试了'OneWayToSource'而不是'OneWay',并且都按预期工作.
Bind(source, target, BindingMode.OneWayToSource);
target.Attribute = "1";
AssertAreEqual(source.Attribute, "1");
source.Attribute = "foo";
target.Attribute = "2";
AssertAreEqual(source.Attribute, "2");
Run Code Online (Sandbox Code Playgroud)
其他详情:
void Bind(TestModel source, TestModel target, BindingMode mode)
{
Binding binding = new Binding();
binding.Source = source;
binding.Path = new PropertyPath(TestModel.AttributeProperty);
binding.Mode = mode;
BindingOperations.SetBinding(target, TestModel.AttributeProperty, binding);
}
class TestModel : DependencyObject
{
public static readonly DependencyProperty AttributeProperty =
DependencyProperty.Register("Attribute", typeof(string), typeof(TestModel), new PropertyMetadata(null));
public string Attribute
{
get { return (string)GetValue(AttributeProperty); }
set { SetValue(AttributeProperty, value); }
}
}
Run Code Online (Sandbox Code Playgroud)
我的代码出了什么问题?
ale*_*2k8 13
设置target.Attribute ="foo"; 清除了绑定.
MSDN:
动态资源和绑定不仅以与本地值相同的优先级运行,它们实际上是本地值,但具有延迟的值.这样做的一个结果是,如果您具有适用于属性值的动态资源或绑定,则您设置的任何本地值随后将完全替换动态绑定或绑定.即使您调用ClearValue来清除本地设置的值,也不会恢复动态资源或绑定.实际上,如果在具有动态资源或绑定的属性上调用ClearValue(没有"文字"本地值),它们也会被ClearValue调用清除.