简体   繁体   中英

Changing background color for WPF DataGrid cell depending on selection and value

I'm trying to achieve this: When the user selects one or multiple cells in a DataGrid all duplicates should have their background color changed .

I have this xaml

<Window x:Class="NotesOnFretboard.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="true"  Margin="12,110,12,29" Name="dataGrid1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" IsReadOnly="True" />
    </Grid>
</Window>

code behind:

public MainWindow()
{
    InitializeComponent();
    DataTable dt = CreateDataTable();

    dataGrid1.ItemsSource = dt.DefaultView;
}

So I populate the datagrid using a DataTable(10 rows, 25 columns). In this datatable there are a number of duplicate values.

When the user selects one or multiple cells in a DataGrid all duplicates should have their background color changed!

Please Help!

// Anders

You could change your collection class so that it has a property to indicate whether it should be highlighted or not, then bind that property (through a converter) to the element property you want to change colour. You'd could respond to a selection/click and change your ItemSource 'selected' property to true/false depending on whatever criteria you desire.

So something like:

<sdk:DataGrid x:Name="NoteList"
    AutoGenerateColumns="False"
    GridLinesVisibility="None"
    HeadersVisibility="None"
    IsReadOnly="True"
    ItemsSource="{Binding NoteList,Mode=OneWay}">
    <sdk:DataGrid.Columns>
        <sdk:DataGridTemplateColumn Width="Auto">
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding NoteDescription, Mode=OneWay}"
                             Background="{Binding NoteHighlighted, 
                                Converter={StaticResource BooleanToColourConverter}}"/>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

您应该使用触发器来实现这一全面指南:设置Microsoft WPF数据网格的样式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM