单向绑定工作停止目标手动更新后 [英] OneWay binding stops working after the target manually updated

查看:126
本文介绍了单向绑定工作停止目标手动更新后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样WPF结合code:

I have such WPF binding code:

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");

第二断言失败!这似乎很奇怪我。

The second assertion fails! This seems odd for me.

另外,我想'OneWayToSource'而不是'单向',一切工作正常。

Also, I tried 'OneWayToSource' instead of 'OneWay', and all works as expected.

Bind(source, target, BindingMode.OneWayToSource);

target.Attribute = "1";
AssertAreEqual(source.Attribute, "1");

source.Attribute = "foo";

target.Attribute = "2";
AssertAreEqual(source.Attribute, "2");

其他详情:

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); }
    }
}

什么是错我的code?

What is wrong with my code?

推荐答案

设置target.Attribute =富;清除绑定。

Setting target.Attribute = "foo"; cleared the binding.

MSDN:

不仅动态资源
  绑定在同一操作
  precedence作为本地价值,他们
  真的是一个局部值,但与
  被推迟的价值。一
  这样的后果是,如果你
  具有动态资源或在结合
  地方属性值,任何地方
  您设置的值之后
  取代了动态绑定或
  完全绑定。即使你打电话
  ClearVa​​lue清除本地设置
  值,动态资源或结合
  将无法恢复。事实上,如果你
  调用ClearVa​​lue对具有属性
  动态资源或代替结合
  (没有文字本地值),他们
  由ClearVa​​lue通话将被清除
  了。

Not only do dynamic resources and bindings operate at the same precedence as a local value, they really are a local value, but with a value that is deferred. One consequence of this is that if you have a dynamic resource or binding in place for a property value, any local value that you set subsequently replaces the dynamic binding or binding entirely. Even if you call ClearValue to clear the locally set value, the dynamic resource or binding will not be restored. In fact, if you call ClearValue on a property that has a dynamic resource or binding in place (with no "literal" local value), they are cleared by the ClearValue call too.

这篇关于单向绑定工作停止目标手动更新后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆