Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get result of a Binding in code

I'm probably searching for this the wrong way, but:

is there any way to get the resulting value of a binding through code?

Probably something glaring obvious, but I just can't find it.

like image 342
Inferis Avatar asked Oct 07 '10 22:10

Inferis


1 Answers

You just need to call the ProvideValue method of the binding. The hard part is that you need to pass a valid IServiceProvider to the method... EDIT: actually, that's not true... ProvideValue returns a BindingExpression, not the value of the bound property.

You can use the following trick:

class DummyDO : DependencyObject
{
    public object Value
    {
        get { return (object)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(object), typeof(DummyDO), new UIPropertyMetadata(null));

}

public object EvalBinding(Binding b)
{
    DummyDO d = new DummyDO();
    BindingOperations.SetBinding(d, DummyDO.ValueProperty, b);
    return d.Value;
}

...

Binding b = new Binding("Foo.Bar.Baz") { Source = dataContext };
object value = EvalBinding(b);

Not very elegant, but it works...

like image 80
Thomas Levesque Avatar answered Oct 08 '22 09:10

Thomas Levesque