All, I am attempting to loop through a WPF DataGrid
using a for each loop to change the background colour of erroneous cells. I have checked many questions but I have yet to find a sufficient answer. What I have so far is
public void RunChecks()
{
const int baseColumnCount = 3;
foreach (DataRowView rv in dataGrid.Items)
{
for (int i = baseColumnCount; i < dataGrid.Columns.Count; i++)
{
if (!CheckForBalancedParentheses(rv.Row[i].ToString()))
{
Color color = (Color)ColorConverter.ConvertFromString("#FF0000");
row.Background = new SolidColorBrush(color); // Problem!
}
}
}
}
The problem is that in order to change the Background
colour of a row in my DataGrid
I need to work with the DataGridRow
object ascociated with the DataRowView
rv
.
How do I get a reference to the DataGridRow
from the object rv
(DataRowView
)?
Thanks for your time.
Edit. Based upon the advice below I now have the following style which works with the mouse over event and set the back and fore font of the relevant cell. However, I am really lost as to how to apply the backcolor to a cell at run-time in my code above. The XML style is
<Window.Resources>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter Property="Background" Value="Red" />
<Setter Property="FontWeight" Value="ExtraBold" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
When you're working with WPF, avoid always accessing UI artifacts directly.
Create in you ModelView a property Color, and bind it to the background color of a single row template of your DataGrid view.
So in order to change the color you will loop throw the ModelView collecton and set/read Color property of every single object binded to every single row. By changing it, if binding is correctly settuped, you will affect row UI color appearance.
For concrete sample you can look on:
How do I bind the background of a data grid row to specific color?
You can use the ItemContainerGenerator
to get the visual representation for your data i.e. DataGridRow
-
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator
.ContainerFromItem(rv);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With