直接设置绑定值 [英] Set the binding value directly

查看:105
本文介绍了直接设置绑定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能后面设置一个双向直接结合的价值,不知道绑定属性?

Is it possible to set the value behind a two-way binding directly, without knowing the bound property?

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

I have an attached property that is bound to a property like this:

<Element my:Utils.MyProperty="{Binding Something}" />

现在我想改变这种状况得到有效保存在的东西从附加属性的角度值。所以我不能直接访问的绑定属性,但只需要在的DependencyObject (即元素实例)的引用和的DependencyProperty 对象本身。

Now I want to change the value that is effectively stored in Something from the perspective of the attached property. So I cannot access the bound property directly, but only have references to the DependencyObject (i.e. the Element instance) and the DependencyProperty object itself.

时只需通过 DependencyObject.SetValue 设置它的问题是,这有效地消除了约束力,但我想改变底层绑定属性。

The problem when simply setting it via DependencyObject.SetValue is that this effectively removes the binding, but I want to change the underlying bound property.

使用 BindingOperations 我可以得到两个绑定 BindingEx pression 。现在是有没有访问属性后面并改变其价值的方式?

Using BindingOperations I can get both the Binding and the BindingExpression. Now is there a way to access the property behind it and change its value?

推荐答案

好吧,我现在已经用自己在绑定前pression一些反思技巧解决了这个。

Okay, I have solved this now myself using a few reflection tricks on the binding expression.

我基本上看结合路径和响应数据项和尝试解决绑定自己。这可能会失败进行更复杂的结合路径,但对于一个简单的属性的名字在上面我的例子,这应该很好地工作。

I basically look at the binding path and the responding data item and try to resolve the binding myself. This will probably fail for more complex binding paths but for a simple property name as in my example above, this should work fine.

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

这篇关于直接设置绑定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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