How to set DataGrid styles when using DataTable as data resources

Fanhua Kong 241 Reputation points
2020-07-24T03:31:07.807+00:00

Hi, guys. When I use ObservableCollection<T> as the data resource for DataGrid, I need to bind each column with a field and can set styles for the column as well. However, when use DataTable as the data resource for DataGrid, I just need to bind the DataTable with the DataGrid as below.
<DataGrid
Grid.Row="0"
x:Name="TransformLoadsDataGrid"
ItemsSource="{Binding TransformerLoads, UpdateSourceTrigger=PropertyChanged}"
CanUserAddRows="False"
CanUserSortColumns="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
GridLinesVisibility="All"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
RowHeaderWidth="0"
BorderBrush="Black"
BorderThickness="0 1 0 1"
Margin="0 0 0 10"
Background="{StaticResource CustomPureWhiteBrush}"
SelectedIndex="{Binding CurrentRowIndex, Mode=TwoWay}">
</DataGrid>
In this way, how could I set styles for columns? Such as text alignment or border styles?
Thanks in advance!

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,765 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,321 Reputation points
    2020-07-24T05:26:00.417+00:00

    Hi,
    UpdateSourceTrigger=PropertyChanged in ItemsSource is not necessary because it has no effect.. You can use Style without Key for all cells or DataGridTemplateColumn for explicit column.

    Because the forum software forbids showing code, I have inserted a picture of the code and the source code as a file.

    13510-x.png13519-x.txt
    13601-x2-2.png


1 additional answer

Sort by: Most helpful
  1. DaisyTian-1203 11,621 Reputation points
    2020-07-24T06:46:31.7+00:00

    You can also use ElementStyle in DataGridTextColumn to set the Property for Text.

     <DataGrid.Columns>  
                        <DataGridTextColumn Header="Name" Width="80" Binding="{Binding cel}" ElementStyle="{StaticResource stlContent}"/>  
        </DataGrid.Columns>  
    

    And set properties in the Style for TextBlock:
    13568-image.png


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.