如何在数据网格中选择堆栈面板时更改背景颜色

本文关键字:颜色 背景 堆栈 选择 数据 数据网 网格 | 更新日期: 2023-09-27 18:14:26

我必须改变StackPanel(存在于DataGrid)的背景颜色,当它被选中或聚焦。

下面是我的XAML:

<DataGrid Background="#DCE1E7" SelectedItem="{Binding Row, Mode=TwoWay}"  AutoGenerateColumns="False" CanUserAddRows="False" HeadersVisibility="None"  GridLinesVisibility="None" HorizontalAlignment="Left" BorderThickness="0" Name="dtlCuisine" VerticalAlignment="Top" BorderBrush="#DCE1E7" VerticalGridLinesBrush="#DCE1E7" HorizontalGridLinesBrush="#DCE1E7"   ColumnWidth="130" SelectionChanged="dtlCuisine_SelectionChanged" CellEditEnding="dtlCuisine_CellEditEnding">
    <DataGrid.Columns>
        <DataGridTemplateColumn x:Name="Template13">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel Name="stkpnlCuisines" Orientation="Horizontal" Background="#DCE1E7" Margin="-1,-1,-1,-1" MouseDown="stkpnlCuisines_MouseDown_1">
                        <Label Content="{Binding CuisineName}" Height="28" HorizontalAlignment="Left" Name="lblCuisineName" VerticalAlignment="Top" FontSize="14" />
                        <StackPanel.Style>
                            <Style TargetType="{x:Type StackPanel}">
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsFocused}" Value="True">
                                        <Setter Property="Background" Value="Red" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </StackPanel.Style>
                    </StackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <StackPanel Margin="-1,-1,-1,-1">
                        <TextBox Name="txtCuisineCategory" AcceptsReturn="True" Text="{Binding CuisineName}" LostFocus="txtCuisineCategory_LostFocus" />
                    </StackPanel>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

改变StackPanelBackground颜色的最好方法是什么

如何在数据网格中选择堆栈面板时更改背景颜色

在DataGridCell上使用IsSelected触发器。如果您不想完全改变所有元素的选定颜色,那么您可以在应用程序资源中使用以下代码:

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#3271B5" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="AliceBlue" />