locked
how to keep DataGrid SelectedRow foreground? RRS feed

  • Question

  • Hi. In DataGrid.LoadingRow event I set the Foreground depending on the data. Now when I select a row, the background turns blue and foreground turns white. I would like only the background to be blue when row is selected but no changes to foreground. How can I keep the original foreground?
    Monday, October 21, 2013 11:49 AM

Answers

  • You should set the Foreground property of the DataGridCells in XAML by specifying a style. You can use DataTriggers to set properties based on the DataContext (the bound data):

        <DataGrid .... >
          <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridCell}" >
              <Style.Triggers>
                <DataTrigger Binding="{Binding DataProperty}" Value="SomeValue">
                  <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding DataProperty}" Value="SomeOtherValue">
                  <Setter Property="Foreground" Value="Green"/>
                </DataTrigger>
                <Trigger Property="IsSelected" Value="True">
                  <Setter Property="Foreground" Value="Red"/>
                </Trigger>
              </Style.Triggers>
            </Style>
          </DataGrid.Resources>
    </DataGrid>

    Using this approach you don't need to handle the LoadingRow event to be able to change the Foreground based on the bound data.

    • Marked as answer by GaiusBaltar Tuesday, October 22, 2013 8:42 AM
    Monday, October 21, 2013 3:14 PM

All replies

  • You should set the Foreground property of the DataGridCells in XAML by specifying a style. You can use DataTriggers to set properties based on the DataContext (the bound data):

        <DataGrid .... >
          <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridCell}" >
              <Style.Triggers>
                <DataTrigger Binding="{Binding DataProperty}" Value="SomeValue">
                  <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding DataProperty}" Value="SomeOtherValue">
                  <Setter Property="Foreground" Value="Green"/>
                </DataTrigger>
                <Trigger Property="IsSelected" Value="True">
                  <Setter Property="Foreground" Value="Red"/>
                </Trigger>
              </Style.Triggers>
            </Style>
          </DataGrid.Resources>
    </DataGrid>

    Using this approach you don't need to handle the LoadingRow event to be able to change the Foreground based on the bound data.

    • Marked as answer by GaiusBaltar Tuesday, October 22, 2013 8:42 AM
    Monday, October 21, 2013 3:14 PM
  • Unfortunetly I can not use this method because in LoadingRow event I do complicated query-s to database and then I set the foreground...
    Tuesday, October 22, 2013 6:10 AM