Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the binding value directly

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?

like image 361
poke Avatar asked Jun 20 '12 13:06

poke


1 Answers

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);
}
like image 66
poke Avatar answered Sep 28 '22 00:09

poke