我该如何解决数据绑定的价值? [英] How do I resolve the value of a databinding?

查看:220
本文介绍了我该如何解决数据绑定的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了翻译的基础上的一个关键字符串标记扩展。示例

I've made a markup extension for translating strings based on a key. Example

<TextBlock Text="{Translate myKey}" />

现在我希望能够使用嵌套绑定提供我的钥匙。例如:

Now I want to be able to use nested bindings for providing my keys. Example:

<TextBlock Text="{Translate {Binding KeyFromDataContext}}" />

当我这样做,我得到一个System.Windows.Data.Binding对象。通过调用ProvideValue并传递下来的ServiceProvider我可以得到一个BindingExpression:

When I do this I get a System.Windows.Data.Binding object. By calling ProvideValue and passing down the ServiceProvider I can get a BindingExpression:

var binding = Key as Binding;
if (binding == null) {
    return null;
}
var bindingExpression = binding.ProvideValue(_serviceProvider) as BindingExpression;
if (bindingExpression == null) {
    return null;
}
var bindingKey = bindingExpression.DataItem;



我能得到这个bindingExpression,但DataItem属性为null。我测试过我的结合是这样

I can get this bindingExpression, but the DataItem property is null. I've tested my binding like this

<TextBlock Text="{Binding KeyFromDataContext}" />

和它工作正常。

任何想法?

推荐答案

不可以可能获得一个绑定的值。你不应该甚至试图做到这一点。 WPF使用一些奇特的反射来解决绑定和信任我 - 你不wan't开始尝试自己那个

It is not possible to get the value of a binding. You're not supposed to be even trying to do this. WPF uses some fancy reflection to resolve the bindings and trust me - you do not wan't to start trying that yourself.

反正考虑到这一点,这就是我落得这样做,这实际上是一个很好的解决方案:

Anyway with that in mind, this is what I ended up doing, which actually is a nice solution:

我做了一个 TranslateConverter 即把翻译的护理:

I made a TranslateConverter that took care of the translation:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var key = value as string ?? parameter as string;

    if (key != null)
    {
    // Do translation based on the key

    }
    return null;
}



然后在我的 TranslateExtension 我只是做到这一点:

var binding = Key as Binding ?? new Binding{Mode = BindingMode.OneWay};
binding.Converter = new TranslateConverter(_targetObject, _targetProperty, Dictionary, Converter);
binding.ConverterParameter = Key is Binding ? null : Key as string;

return binding.ProvideValue(serviceProvider);

此方式的结合是通过WPF解决并传递到转换器的值,一简单的文本-key传递到转换器作为参数中。

This way a binding is resolved by WPF and is passed to the converter as value, while a simple text-key is passed to the converter as a paramter.

_targetObject _targetProperty 从获得的ServiceProvider。

_targetObject and _targetProperty are obtained from the ServiceProvider.

这篇关于我该如何解决数据绑定的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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