Search code examples
c#windows-phone-7xamlivalueconverter

How to pass a static value to IValueConverter in XAML


I would like to use static texts fetched from a web service in my WP7 app. Each text has a Name (the indetifier) and a Content property.

For example a text could look like this:

Name = "M43";
Content = "This is the text to be shown";

I would then like to pass the Name (i.e. the identifier) of the text to an IValueConverter, which would then look up the the Name and return the text.

I figured the converter to look something like this:

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

        return null;
    }
}

Then in the XAML:

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

...

<TextBlock Text="{Binding 'M43', Converter={StaticResource StaticTextConverter}}"/>

However, this does not seem to work and I am not sure that I pass in the value to the converter correctly.

Does anyone have some suggestions?


Solution

  • I finally found the answer. The answer was a mix between that of @Shawn Kendrot and another question I asked here: IValueConverter not getting invoked in some scenarios

    To summarize the solution for using the IValueConverter I have to bind my control in the following manor:

    <phone:PhoneApplicationPage.Resources>
        <Helpers:StaticTextConverter x:Name="TextConverter" />
    </phone:PhoneApplicationPage.Resources>
    
    <TextBlock Text="{Binding Converter={StaticResource TextConverter}, ConverterParameter=M62}" />
    

    Since the ID of the text is passed in with the converter parameter, the converter looks almost the same:

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

    However, as it turns out, the binding and thus the converter is not invoked if it does not have a DataContext. To solve this, the DataContext property of the control just has to be set to something arbitrary:

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

    And then everything works as intended!