Search code examples
wpfdata-bindingwpfdatagrid

How to change style of data grid cell based on conditional operator in WPF


I am working on a wpf application to show record and i need to change style of text in a particular column "Price" if it is lesser than 50. Code is given as below:

 <DataGrid ItemsSource="{Binding Path= Shares}" HorizontalAlignment="Left" Margin="89,201,0,0" CanUserAddRows="False" AutoGenerateColumns="False" VerticalAlignment="Top" Height="280" Width="500">
       <DataGrid.Columns>
            <DataGridTextColumn Header="Company" Binding="{Binding CompanyName}" Width="250" />
            <DataGridTextColumn Header="Share Price" Binding="{Binding Price}" />                       
        </DataGrid.Columns>
    </DataGrid>

So i need to change foreground color of price text if it is < 50.

Can you please suggest how to do it?


Solution

  • You can't do this kind of comparisons in XAML since there is no < operator defined but you could use a converter:

    <DataGrid ItemsSource="{Binding Path= Shares}" HorizontalAlignment="Left" Margin="89,201,0,0" CanUserAddRows="False" AutoGenerateColumns="False" 
                      VerticalAlignment="Top" Height="280" Width="500"
                      xmlns:local="clr-namespace:WpfApplication1">
        <DataGrid.Resources>
            <local:MyConverter x:Key="conv" />
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTextColumn Header="Company" Binding="{Binding CompanyName}" Width="250" />
            <DataGridTextColumn Header="Share Price" Binding="{Binding Price}">
                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="TextBlock">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Price, Converter={StaticResource conv}}" Value="True">
                                <Setter Property="Foreground" Value="Green" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    

    namespace WpfApplication1
    {
        public class MyConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                decimal d = System.Convert.ToDecimal(value);
                return d < 50;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotSupportedException();
            }
        }
    }
    

    The Convert method returns true if the Price property is < 50 and then the Foreground of the TextBlock is changed to Green.