简体   繁体   中英

Change background of WPF DataGrid cell depending on value when populated with a datatable as IListSource

I have seen similar posts like this

However, they don't seem to answer my question. I have a XAML datagrid in a WPF application

<DataGrid AutoGenerateColumns="True" Grid.Row="1" AlternationCount="2" HeadersVisibility="Column" Name="dgSkillsMatrix" Margin="0,0,0,1" HorizontalGridLinesBrush="White" VerticalGridLinesBrush="White" AlternatingRowBackground="#FFD0D0EB" RowBackground="#FFECECF5" FontSize="12">
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Value}" Value="1">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Content}" Value="2">
                    <Setter Property="Background" Value="Green"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Text}" Value="1">
                    <Setter Property="Background" Value="Black"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Name}" Value="Temp">
                    <Setter Property="Background" Value="Black"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

As you can see, I have tried a number of different ways to "Trigger" the colour change, but none of them fire. If I put a generic setting in abouve the triggers it will change the colour.

I think the problem is that I am binding to the datagrid from a dynamic set of data that could change day to day, so I am using a datatable (below), as there is a varying number of coulmns that mean I can't use objects for each row, as I never know when the number of columns/properties would change.

this.dgSkillsMatrix.ItemsSource = (dt as IListSource).GetList();

I just need to know how to fire a trigger to change properties depending on that value of a cell created from a datatable to listsource.

Does this link offer any assistance? It appears that binding to a DataTable may cause a few issues for cell colouring, have you tried implementing a data converter and MultiDataBinding as the article suggests?

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