在 DataGrid 的选定行中设置元素的前景色

set Foreground color of element inside Selected Row of DataGrid

我有一个定义如下的 DataGridTemplateColumn。如果选择了该行,我需要将两个文本块的前景 属性 更改为白色

<DataGrid.Columns>
<DataGridTemplateColumn  Header="User" Width="240" >
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Margin="10,3,0,0" Foreground="#1c72c7" >
                        <Run Text="{Binding FullName, Mode=OneWay}" />
                </TextBlock>
                <Label Padding="0,0,0,0"  Margin="0,0,0,3">
                    <TextBlock Foreground="#1c72c7"  Margin="10,0,0,0" TextDecorations="Underline" Text="{Binding DisplayName}" />
                </Label>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

我已经定义了一个 RowStyle 来改变行的背景颜色,如下所示

 <DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{x:Static SystemColors.HighlightColor}" />
    </Style.Resources>

</Style>

您应该为每个人 TextBlock 修改 Style,并根据需要添加行为,如下所示:

 <Style x:Key="FirstTextBlockStyle" TargetType="TextBlock">
    <Setter Property="Foreground" Value="Black" />
    <Style.Triggers>
       <DataTrigger Binding="{Binding IsSelected, 
             RelativeSource= {RelativeSource 
                                AncestorType={x:Type DataGridRow}}}" 
             Value="True">
           <Setter Property="Foreground" Value="White" />
        </DataTrigger>
     </Style.Triggers>
 </Style>