Search code examples
c#winui-3

How to change DataGrid style dictionary by Setter via C# in WinUI3?


I have a DataGrid (CommunityToolkit.Controls), and I need to change some default style parameters. I can do it in XAML code via Setters. But I must do it programatically via C#. Can you give some C# examples how to make GridView style Setters to me? Thanks.


Solution

  • Let's say you have an DataGrid named DataGridControl. In code-behind you can set the Style programmatically like this:

    var customStyle = new Style(typeof(DataGrid));
    
    if (this.DataGridControl.Style is Style baseStyle)
    {
        customStyle.BasedOn = baseStyle;
    }
    
    customStyle.Setters.Add(new Setter(DataGrid.RowHeightProperty, 50));
    
    this.DataGridControl.Style = customStyle;