Question

In WP8 I would like to set the foreground color of a TextBlock to a different color based on a boolean property in my binding. Furthermore, I would also like to use a StaticResource for the color.

One possibility I have looked into is using a ValueConverter for this but couldn't get it to work so far with the StaticResources. The code that I tried was something like :

<TextBlock Foreground="{Binding IsBlue, Converter={StaticResource BoolToColorConverter}}" />

And my converter (I didn't think that returning a string will work but decided to test it anyway):

public class BoolToColorConverter : IValueConverter{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
        return (value is bool && (bool)value) ? "{StaticResource PhoneAccentBrush}" : "{StaticResource PhoneSubtleBrush}";
        }
}

Furthermore, I looked into using DataTriggers but I saw that WP8 doesn't have direct support for them.

I haven't yet tried a dependency property because I wanted to make sure first that I am not missing a simpler and more obvious way to fix that.

What is the best way to create that?

Was it helpful?

Solution

You have two ways to solve this issue:

You can extend your converter by additional properties which will be filled by the binding

public class BooleanToBrushConverter
        : IValueConverter
    {
        public Brush TrueBrush { get; set; }
        public Brush FalseBrush { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is bool)
            {
                return (bool) value
                    ? TrueBrush
                    : FalseBrush;
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Now you can initialize it by the page resources

<BooleanToBrushConverter x:Key="BooleanToBrushConverter" TrueBrush="{StaticResource PhoneAccentBrush}" FalseColor="{StaticResource PhoneSubtleBrush}" />

And use it as easy as

<TextBlock Foreground="{Binding IsBlue, Converter={StaticResource BooleanToBrushConverter}}" />

The second solution is the fix of your code to recover brushes from the application resources

public class BoolToColorConverter
  : IValueConverter{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

        return (value is bool && (bool)value) ? Application.Current.Resources["PhoneAccentBrush"] : Application.Current.Resources["PhoneSubtleBrush"];
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top