How do I resolve the value of a databinding inside a MarkupExtension?

后端 未结 2 1536
名媛妹妹
名媛妹妹 2020-12-06 07:47

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


Now I want to

2条回答
  •  佛祖请我去吃肉
    2020-12-06 08:11

    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:

    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;
    }
    

    Then in my TranslateExtension I simply do this:

    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);
    

    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 and _targetProperty are obtained from the ServiceProvider.

提交回复
热议问题