4thSpace 4thSpace - 3 months ago 27
C# Question

How to reuse WPF styles?

I have a style that I'm using on several columns of a Datagrid.

<DataGridTextColumn ...>
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter .../>
<Setter .../>
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>


I'm replicating the above style code for all columns. Is there some way to do this without replicating the code?

Answer

Put this in a ResourceDictionary or the parent control's(the Window or DataGrid) Resources:

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

And you can reuse it like this:

<DataGrid>
    <DataGridTextColumn EditingElementStyle="{StaticResource TextColumnEditStyle}"></DataGridTextColumn>
    <DataGridTextColumn EditingElementStyle="{StaticResource TextColumnEditStyle}"></DataGridTextColumn>
</Datagrid>