Как применить стиль ячейки к ячейке 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
<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
, но ресурс не может быть разрешен. Я импортировал правильный словарь ресурсов, поскольку другие стили работают Что я делаю неправильно здесь?
Спасибо за ваше время.
Ответы
Ответ 1
Поскольку ваш Style
не имеет Key
, вам не нужно устанавливать CellStyle
в DataGrid
, он будет применяться ко всем DataGridCell
по умолчанию.
Если вы не хотите, чтобы он применялся ко всем DataGridCell
, по умолчанию укажите стиль a 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}" />
Ответ 2
Чтобы применить стиль только к некоторому 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>