I had this same issue and figured it out after making a minimal test and some deductive reasoning!
Basically the solution is to ALWAYS
make sure you set the background color (or any style in fact).
Don't assume any defaults for row styling. I was assuming
a default of white - which is a
reasonable assumption but was not actually the case.
More details:
It looks like the runtime reuses instances of the Row class when rendering multiple rows. I haven't verified this at all but judging from the symptoms it seems like that must be happening.
I had only one or two rows that ought to be colored differently. I was seeing randomly colored rows when scrolling up and down.
Here is my test class i made. Every fifth row is supposed to be red and italic.
You'll see a couple lines commented out (that set a default of non-italic and white background). With these commented out - if you scroll up and down you will see a lot of red!! This is because the row objects are being reused. If you make the window smaller and then maximize it some of the white will come back. Probably garbage collector collecting rows it doesn't think you'll need any more after having made the window smaller.
As i said above the solution is to always specify styles for defaults and don't assume any defaults.
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
dataGrid1.ItemsSource = Enumerable.Range(0, 50).Select(x => new Person()
{
FirstName = "John",
LastName = "Smith",
ID = x,
Delinquent = (x % 5 == 0) // every fifth person is 'delinquent'
});
}
private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
{
var person = (Person)e.Row.DataContext;
if (person.Delinquent)
{
e.Row.Background = new SolidColorBrush(Colors.Red);
e.Row.Foreground = new SolidColorBrush(Colors.White);
e.Row.FontStyle = FontStyles.Italic;
}
else
{
// defaults - without these you'll get randomly colored rows
// e.Row.Background = new SolidColorBrush(Colors.Green);
// e.Row.Foreground = new SolidColorBrush(Colors.Black);
// e.Row.FontStyle = FontStyles.Normal;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
public bool Delinquent { get; set; }
}
}