如何使wpf DataGridRow所选颜色覆盖DataGridCell的绑定背景色
本文关键字:DataGridCell 覆盖 绑定 背景色 颜色 何使 wpf DataGridRow | 更新日期: 2023-09-27 18:22:24
我有一个DataGridTemplateColumn,它定义了一个绑定了Background和Foreground属性的TextBlock。这允许颜色根据绑定属性的值进行更改。到目前为止一切都很好,只是我希望默认选择的行颜色覆盖我绑定的背景颜色。如何在xaml中执行此操作?
<DataGridTemplateColumn Header="Text">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Text}"
Background="{Binding Path=BackgroundColor}"
Foreground="{Binding Path=ForegroundColor}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
最终,我似乎需要确定单元格是否在所选行中。如果是,请使用默认选定的行背景色,否则使用绑定的背景色。我不知道该怎么做。如有任何帮助,我们将不胜感激。
您可以避免直接绑定Background
,而是将Style
分配给TextBlock
,后者在选择({Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}}
)为false
时使用DataTrigger
,然后才将Background
设置为绑定。
这不是最优雅的解决方案,但它相当简单。。。
将"CurrentBackgroundColor"属性添加到您的Item(需要实现已更改的属性),默认情况下您将其设置为BackgroundColor。这就是您将背景绑定到的内容。
使用以下逻辑将DataGrid的双向SelectedItem绑定添加到属性:
public Item SelectedItem
{
get
{
return selectedItem;
}
set
{
if (selectedItem != value)
{
if (selectedItem != null)
{
selectedItem.CurrentBackgroundColor = selectedItem.BackgroundColor;
}
selectedItem = value;
if (selectedItem != null)
{
selectedItem.CurrentBackgroundColor = null;
}
RaisePropertyChanged("SelectedItem");
}
}
}
这是
- 如果存在当前选定的项目,请将其背景更改回默认值
- 将selectedItem更新为新选择的项目
- 通过将CurrentBackgroundColor设置为null来清除它。这将允许显示选择突出显示
如果你想要一个更优雅的解决方案,我会研究EventTriggers