Use XAML resource in WPF IValueConverter

If you don’t want to hardcoded styles and colors in you WPF, Silverlight or WP7 project you’ve probably added some styles and predefined colors in the APP.XAML file:

<Style TargetType="TextBlock" x:Key="Style1">
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeLarge}"/>
    <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiLight}"/>        
</Style>
<Style TargetType="TextBlock" x:Key="Style2">
    <Setter Property="Foreground" Value="Red"/>
    <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMedium}"/>
    <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiLight}"/>         
</Style>

Using these in a regular XAML file is simple. But when you need to use it in a ValueConverter, you need a little trick:

public class StyleConverter : IValueConverter
{
 
	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
	{
		Style result;
		if (value is bool && !(bool)value)
		{
			result = (Style)App.Current.Resources["Style2"];
		}
		else
		{
		     result = (Style)App.Current.Resources["Style1"];
		}
		return result;
	}
 
	public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
	{
		throw new NotImplementedException();
	}
}

It took me some time to find.

Comments are closed.