简体   繁体   中英

How to make wpf DataGridRow selected color override bound background color of DataGridCell?

I have a DataGridTemplateColumn that defines a TextBlock which has bound Background and Foreground properties. This allows the colors to change based on the value of the bound property. So far so good, except I want the default selected row color to override my bound background color. How can I do this in xaml?

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

Ultimately, it seems like I need to determine if the cell is in the selected row. If so, use the default selected row background color else use the bound background color. I am not sure how to aproach this. Any help would be appreciated.

DataTrigger直接绑定Background ,而是将Style分配给TextBlock ,该DataTrigger在选择( {Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}} )上使用DataTrigger时将其设置为false ,然后仅将Background设置为绑定。

This is not the most elegant solution, but it's fairly simple...

Add a 'CurrentBackgroundColor' property to your Item (needs to implement property changed), which by default you set to the BackgroundColor. This is what you bind your Background to.

Add a two-way SelectedItem binding to your DataGrid to a property with the following logic:

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");
    }
  }
}

What this does is

  • If there is a currently selected item, change its background back to its default value
  • Updated selectedItem to the newly selected item
  • Clear the CurrentBackgroundColor by setting it to null. This will allow the selection highlight to be shown

If you were after a more elegant solution I would look into EventTriggers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM