Set the binding value directly

poke picture poke · Jun 20, 2012 · Viewed 7.5k times · Source

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}" />

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.

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.

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?

Answer

poke picture poke · Jun 20, 2012

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