Reputation: 1034
I am using a gridview inside a listview.My grid view has two colums ID and Result.I am loading the gridview from a List.So result column has two types of values positive and negative.I want to display text color green for positive and red for negative and also attach an icon alongside the textblock.
Is it possible in xaml ? Or am i trying to implement which is not possible ?
How to bind the color based on the values coming from the list into the grid ?
<ListView Height="166" HorizontalAlignment="Left" Margin="23,0,0,0" Name="lvStatus" VerticalAlignment="Top" Width="264">
<ListView.View>
<GridView>
<GridViewColumn Header="Result">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Result}"/>
<Image ></Image>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
Upvotes: 1
Views: 3749
Reputation: 132548
Create a Converter
that returns Green
if the specified value is above 0, and Red
if it is below 0, and use it to determine the Foreground color of your Text
public class NumberToColorBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is double)
{
return (((double)value) > 0 ? Brushes.Green : Brushes.Red);
}
throw new Exception("Invalid Value");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
You can then use your converter like this:
<Window.Resources>
<local:NumberToColorBrushConverter x:Key="NumberToColorBrushConverter" />
</Window.Resources>
<TextBlock Text="{Binding Result}" Foreground={Binding Result,
Converter={StaticResource NumberToColorBrushConverter}}" />
Edit
If you have a value in your data which determines Positive or Negative, then you don't even need to use a Converter. Here's an example that uses a DataTrigger
<Window.Resources>
<Style x:Key="ResultTextBlockStyle" TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Setter Property="Foreground" Value="Green" />
<DataTrigger Binding="{Binding PositiveOrNegative}" Value="Negative">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<TextBlock Text="{Binding Result}" Style="{StaticResource ResultTextBlockStyle}" />
Upvotes: 1