windowskm windowskm - 1 month ago 8
C# Question

Programmatically Change Cell Colour

I have two lists of

which I need to place into two vertical columns side by side. Where the numbers do not match I need to hightlight this (one or both cells, doesn't matter which. Changing background or font colour, doesn't matter which).

I initially was displaying these in side by side
but when I found it hard to change the colour of a specific cell programmatically I started looking at
, but this too proved difficult + many of the guides I found online appear to be Windows Forms focused, not WPF.

For what I thought would be a simple task what would be the recommended control and please guide me as to how to identify these differing cells/indexes and also update their appearance.

Extra info: Both lists will not be terribly long (<15 each).

I have tried this when I was using the datagrid;

dgdResults.Rows[0].Cells[0].Style.BackColor = Color.Red;

Answer Source

DataGrid/ListBox are ItemsControls and work well with a single collection. I suggest to create additional list of objects with a pair of items from list1 and list2 and attribute which indicates different items, and then display that list in UI.

var L1 = new List<int> {1, 2, 3, 4, 5};
var L2 = new List<int> {1, 2, 0, 4, 5};
var results = L1.Zip(L2, (i, j) => new {Previous = i, Current = j, IsDifferent = i != j});
ListResults.ItemsSource = results;
<ItemsControl Name="ListResults">
            <UniformGrid Rows="1">
                    <Style TargetType="UniformGrid">
                          <DataTrigger Binding="{Binding Path=IsDifferent}" Value="true">
                            <Setter Property="Background" Value="Crimson"/>
                <Label Content="{Binding Path=Previous}"/>
                <Label Content="{Binding Path=Current}"/>


Attribute IsDifferent is used in a DataTrigger to change background