如何将单元格样式应用于DataGrid单元格 [英] How to Apply a Cell Style to DataGrid Cell

查看:141
本文介绍了如何将单元格样式应用于DataGrid单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 DataGrid

<DataGrid x:Name="cultureDataGrid" 
          Grid.Row="1" 
          CellStyle="{StaticResource DataGridCell}"
          ItemsSource="{Binding Cultures, 
                                NotifyOnSourceUpdated=True, 
                                UpdateSourceTrigger=PropertyChanged, 
                                Mode=TwoWay, 
                                IsAsync=True}" 
          Style="{x:Null}" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="Code" Binding="{Binding Code}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Language" Binding="{Binding Language}" IsReadOnly="True"/>
        <DataGridTextColumn Header="LocalName" Binding="{Binding LocalName}" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

我具有以下单元格样式来更改选定的 Backcolor

I have the following cell style to change the selected Backcolor

<Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
    <Setter Property="Background" Value="White"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="Red"/>
            <Setter Property="Foreground" Value="White"/>
        </Trigger>
    </Style.Triggers>
</Style>

我尝试应用 CellStyle = {StaticResource DataGridCell}

I have tried applying the CellStyle="{StaticResource DataGridCell}" as shown above, and using DynamicResource but the resource is failing to be resolved. I have imported the correct resource dictionary as other styles are working What am I doing wrong here?

感谢您的时间。

推荐答案

因为您的样式没有密钥,您不必在 DataGrid 上设置 CellStyle ,它将应用于所有 DataGridCell 默认情况。

Since your Style has no Key you do not have to set CellStyle on the DataGrid, it will be applied to all DataGridCell by default.

如果您不希望将其应用于所有 DataGridCell 默认情况下,为样式指定 x:Key 并在 DataGrid上设置 CellStyle 。 code>

If you dont want it applied to all DataGridCell by default give the style an x:Key and set the CellStyle on the DataGrid

示例:

<Style x:Key="MyDataGridCell" TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
    <Setter Property="Background" Value="White"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="Red"/>
            <Setter Property="Foreground" Value="White"/>
        </Trigger>
    </Style.Triggers>
</Style>

<DataGrid CellStyle="{StaticResource MyDataGridCell}" />

这篇关于如何将单元格样式应用于DataGrid单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆