在代码中获取绑定的结果 [英] Get result of a Binding in code

查看:98
本文介绍了在代码中获取绑定的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能正在寻找错误的方式,但是:

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.

推荐答案

您只需要调用绑定的 ProvideValue 方法。很难的部分是你需要传递一个有效的 IServiceProvider 到方法... 编辑:实际上,这不是真的... ProvideValue 返回一个 BindingExpression ,而不是绑定属性的值。

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... actually, that's not true... ProvideValue returns a BindingExpression, not the value of the bound property.

您可以使用以下技巧:

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

这篇关于在代码中获取绑定的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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