Get result of a Binding in code

后端 未结 1 1079
栀梦
栀梦 2021-02-08 09:53

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, b

1条回答
  •  再見小時候
    2021-02-08 10:35

    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...

    0 讨论(0)
提交回复
热议问题