Partilhar via


Code sample for the WPF DataGrid.CellStyle topic

At the deadline for Visual Studio 10 Beta 1 content complete, I was madly trying to check in art and code for the DataGrid APIs.  I thought I got it all in but failed to click submit to actually finish uploading the code for CellStyle.  So if you are interested, here is a little sample code.  Using styles in DataGrid is an amazingly powerful way to accomplish a lot without writing much code. 

The following example uses a trigger to change the Background color of a DataGridCell when the cell is selected.

        <DataGrid Name="DG1" ItemsSource="{Binding}" SelectionUnit="Cell" >

            <DataGrid.CellStyle>

                <Style TargetType="DataGridCell" >

                    <Style.Triggers>

                        <Trigger Property="IsSelected" Value="True">

                            <Setter Property="Background" Value="SeaGreen"/>

                        </Trigger>

                    </Style.Triggers>

                </Style>

            </DataGrid.CellStyle>

        </DataGrid>

The ItemsSource is an ObservableCollection of Animal objects:

public class Animal

        {

            public Animal()

            {

            }

            public Animal(string name)

            {

                Name = name;

            }

            public string Name { get; set; }

        }

This code produces the following output.

A selected cell with a green background

Comments