Reputation: 1147
I need to print in a textBlock repeat if a number is less than 80 and paint color red, and more or equal than 80 print successful with green color.
How can I do that in XAML?
Upvotes: 2
Views: 245
Reputation: 184526
Sadly there are no inequality-triggers or the like, so using a converter should do.
<TextBlock>
<TextBlock.Foreground>
<Binding Path="TestDouble">
<Binding.Converter>
<vc:ThresholdConverter BelowValue="{x:Static Brushes.Red}"
AboveValue="{x:Static Brushes.Green}"
Threshold="80" />
</Binding.Converter>
</Binding>
</TextBlock.Foreground>
<TextBlock.Text>
<Binding Path="TestDouble">
<Binding.Converter>
<vc:ThresholdConverter BelowValue="Repeat"
AboveValue="Successful"
Threshold="80" />
</Binding.Converter>
</Binding>
</TextBlock.Text>
</TextBlock>
public class ThresholdConverter : IValueConverter
{
public double Threshold { get; set; }
public object AboveValue { get; set; }
public object BelowValue { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double input;
if (value is double)
{
input = (double)value;
}
else
{
var converter = new DoubleConverter();
input = (double)converter.ConvertFrom(value);
}
return input < Threshold ? BelowValue : AboveValue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Upvotes: 3
Reputation: 2401
<local:NumberToBrushConverter x:Key="numberToBrushConverter" />
<local:NumberToTextConverter x:Key="numberToTextConverter" />
<TextBlock Background="{Binding Number, Converter={StaticResource numberToBrushConverter}}"
Text="{Binding Number, Converter={StaticResource numberToTextConverter}"/>
class NumberToBrushConverter: IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int number = (int)value;
return number < 80 ? Brushes.Red : Brushes.Green;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
#endregion
}
The other converter would look similar to the brush converter, but return "Successful" or "Repeat".
Upvotes: 2