如何将单元格样式应用于DataGrid单元格

时间:2013-09-04 20:53:36

标签: c# wpf datagrid styles

我有以下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

<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}",如上所示,并使用DynamicResource,但资源无法解析。我已经导入了正确的资源字典,因为其他样式正在运行我在这里做错了什么?

感谢您的时间。

2 个答案:

答案 0 :(得分:14)

由于Style没有Key,您不必在CellStyle上设置DataGrid,默认情况下它将应用于所有DataGridCell

如果您不希望它在默认情况下应用于所有DataGridCell,请将样式设为x:Key,并在CellStyle上设置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}" />

答案 1 :(得分:3)

仅将样式应用于某些DataGridRow:

创建DataGridCell样式:

< !-- DataGridCell Style-->
< Style x:Key="MyDataGridCellStyle" TargetType="{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 -->
<DataGrid >
    <DataGrid.Columns>
        <DataGridComboBoxColumn CellStyle="{StaticResource MyDataGridCellStyle}" />
        <DataGridTextColumn CellStyle="{StaticResource MyDataGridCellStyle}" />
    </DataGrid.Columns>
</DataGrid>