直接设置绑定值

pok*_*oke 7 wpf binding attached-properties

是否可以直接在双向绑定后面设置值,而不知道绑定属性?

我有一个附加属性绑定到这样的属性:

<Element my:Utils.MyProperty="{Binding Something}" />
Run Code Online (Sandbox Code Playgroud)

现在我想Something从附加属性的角度更改有效存储的值.所以我不能直接访问绑定属性,而只能引用DependencyObject(即Element实例)和DependencyProperty对象本身.

简单地设置它的问题DependencyObject.SetValue是这有效地删除了绑定,但我想更改底层绑定属性.

使用BindingOperations我可以得到BindingBindingExpression.现在有办法访问它背后的属性并改变它的价值吗?

pok*_*oke 6

好的,我现在自己解决了这个问题,在绑定表达式上使用了一些反射技巧。

我基本上查看绑定路径和响应数据项并尝试自己解决绑定。对于更复杂的绑定路径,这可能会失败,但对于我上面的示例中的简单属性名称,这应该可以正常工作。

BindingExpression bindingExpression = BindingOperations.GetBindingExpression(dependencyObj, dependencyProperty);
if (bindingExpression != null)
{
    PropertyInfo property = bindingExpression.DataItem.GetType().GetProperty(bindingExpression.ParentBinding.Path.Path);
    if (property != null)
        property.SetValue(bindingExpression.DataItem, newValue, null);
}
Run Code Online (Sandbox Code Playgroud)