4thSpace 4thSpace - 2 months ago 18
C# Question

How to create generic editing style for DataGridCheckBoxColumn?

I've created the following style for a DataGrid DataGridCheckBoxColumn:

<Style x:Key="TextColumnEditStyle" TargetType="TextBox">
<Setter...>
<Setter...>
</Style>


Then on the DataGrid:

<DataGridCheckBoxColumn EditingElementStyle="{StaticResource TextColumnEditStyle}"...>


That's work fine.

Is there a way to make the above a more generic style that targets DataGridCheckBoxColumn so I don't have to assign the style to each DataGridCheckBoxColumn?

I have tried the following but it had no effect:

<Style TargetType="DataGridCheckBoxColumn">
<Setter...>
<Setter...>
</Style>


...and then removed the style assignment:

<DataGridCheckBoxColumn ...>

Answer

You can create a custom column with this style set to it, and then instead of adding DataGridCheckBoxColumn you can add your own custom column and that will have your style applied

Create a new column say MyColumn so MyColumn.xaml looks like

<DataGridCheckBoxColumn  x:Class="TestApp.MyColumn"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:TestApp"
             EditingElementStyle="{StaticResource TextColumnEditStyle}"
             mc:Ignorable="d"/>

and MyColumn.xaml.cs looks like

public partial class MyColumn : DataGridCheckBoxColumn
{
    public MyColumn()
    {
        InitializeComponent();
    }
}

and then your view that uses grid can use it like this

<Grid>
    <DataGrid ItemsSource="{Binding Items}">
        <DataGrid.Columns>
            <local:MyColumn Binding="{Binding .}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

you can create TextColumnEditStyle in a resource that will be used by new custom column.

Comments