如何在datagrid中选择时更改堆栈面板的背景颜色

时间:2013-05-20 07:00:18

标签: c# wpf

当选择或聚焦时,我必须更改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>

更改Background的{​​{1}}颜色的最佳方法是什么。

1 个答案:

答案 0 :(得分:1)

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

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