首页 文章

如何让wpf DataGridRow选中颜色覆盖DataGridCell的绑定背景颜色?

提问于
浏览
1

我有一个DataGridTemplateColumn定义了一个TextBlock,它绑定了Background和Foreground属性 . 这允许颜色根据绑定属性的值进行更改 . 到目前为止一切都那么好,除了我希望默认选择的行颜色覆盖我的绑定背景颜色 . 我怎么能在xaml中这样做?

<DataGridTemplateColumn Header="Text">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Text}"
                       Background="{Binding Path=BackgroundColor}"
                       Foreground="{Binding Path=ForegroundColor}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

最终,似乎我需要确定单元格是否在所选行中 . 如果是这样,请使用默认选定的行背景颜色,否则使用绑定的背景颜色 . 我不知道如何接受这个 . 任何帮助,将不胜感激 .

2 回答

  • 1

    您可以避免直接绑定 Background 而是将Style分配给 TextBlock ,它在选择( {Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}} )上使用DataTriggerfalse ,然后才将 Background 设置为绑定 .

  • 0

    这不是最优雅的解决方案,但它相当简单......

    将“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

相关问题