IValueConverter not getting invoked in some scenarios

爷,独闯天下 提交于 2019-12-24 08:16:11

问题


I am using a collection of texts fetched from a web service, which should be used for a variety of controls.

The easiest and most dynamic way to do this, in my opinion, is to use an IValueConverter to get the given text as follows:

public class StaticTextConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter != null && parameter is string)
        {
            return App.StaticTexts.Items.SingleOrDefault(t => t.Name.Equals(parameter)).Content;
        }

        return null;
    }
}

And then in the XAML I give the ID of the text ('Name') to the converter:

<phone:PhoneApplicationPage.Resources>
    <Helpers:StaticTextConverter x:Name="TextConverter" />
</phone:PhoneApplicationPage.Resources>

<TextBlock Text="{Binding Converter={StaticResource TextConverter}, ConverterParameter=M62}" />

Then to change the text of some control, all that has to be done is to either change the ID in the parameter or change the text itself from some web interface.

My problem is

That the value converter only gets invoked when in some sort of DataTemplate context where the ItemSource has been set, as if the Binding property only works there.

Whenever I use this method anywhere else, the value converter is simply not invoked.

Does anyone have an idea of what I might be doing wrong?


回答1:


Set DataContext="object" for your textblocks where the convertet is not working and the value converter will be invoked.

This workaround will do the trick in your scenario.




回答2:


add source for the binding

use something like that

Text="{Binding  Converter={StaticResource LocalizedStringsConventer} ,ConverterParameter=Wrong, Source=NULL}"


来源:https://stackoverflow.com/questions/11843551/ivalueconverter-not-getting-invoked-in-some-scenarios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!