Search code examples
c#windows-phone-7xamlivalueconverter

IValueConverter not getting invoked in some scenarios


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?


Solution

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