Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a style for the datagrid.columns

I'm still struggling on something. All examples i see on the internet apply datagrid.columns in the resources of the datagrid itself. I don't want that. I want to define a template or style in the window.resources which has to apply to the datagrid through binding. Can i and how can i do that? This is the xaml in my control's resources :

        <DataGrid Name="dgFruit" ItemsSource="{Binding}" AutoGenerateColumns="false" Style="{StaticResource datagrid}" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name"/>
                <DataGridTextColumn Binding="{Binding Path=Color}" Header="Color"/>
                <DataGridCheckBoxColumn Binding="{Binding Path=Mjummy}" Header="Mjummy"/>
                <DataGridTextColumn Binding="{Binding Path=Number}" Header="Number"/>
                <DataGridTextColumn Binding="{Binding Path=Pits.Count}" Header="Pits"/>
            </DataGrid.Columns>
        </DataGrid>
like image 227
Terry Avatar asked Jan 27 '26 16:01

Terry


1 Answers

You cannot do that as far as i know since there is no set-accessor for the DataGrid.Columns property, otherwise it could be set in a Style using a Setter.

You can only set columns directly, you cannot bind them using a collection either it seems.

Here is a very roundabout and ugly way to get the same columns in multiple grids:

Resources:

<x:Array x:Key="MyColumns" Type="{x:Type DataGridColumn}">
    <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name"/>
    <DataGridTextColumn Binding="{Binding Path=Color}" Header="Color"/>
    <DataGridCheckBoxColumn Binding="{Binding Path=Mjummy}" Header="Mjummy"/>
    <DataGridTextColumn Binding="{Binding Path=Number}" Header="Number"/>
    <DataGridTextColumn Binding="{Binding Path=Pits.Count}" Header="Pits"/>
</x:Array>

Datagrid:

<DataGrid ... Loaded="dataGrid_Loaded"/>

Event:

private void dataGrid_Loaded(object sender, RoutedEventArgs e)
{
    DataGridColumn[] columns = Resources["MyColumns"] as DataGridColumn[];
    DataGrid dg = sender as DataGrid;
    dg.Columns.Clear();
    foreach (var item in columns)
    {
        dg.Columns.Add(item);
    }
}
like image 82
H.B. Avatar answered Jan 31 '26 01:01

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!