Reputation: 13
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.
Upvotes: 1
Views: 2478
Reputation: 5110
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 you were after a more elegant solution I would look into EventTriggers
Upvotes: 0
Reputation: 185553
You could refrain from directly binding the Background
to instead assign a Style
to the TextBlock
which uses a DataTrigger
on the selection ({Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}}
) being false
and only then sets the Background
to the binding.
Upvotes: 1