I have a CustomControl which contains among other things a DataGrid. One time I use this CustomControl I need to do a small change to the appearance of the DataGrid CellStyle.
What I am doing right now is Duplicating my whole CustomControl Style in XAML just to change the CellStyle. So I would like to keep my base cell style and only overwrite the DataGrid CellStyle. Therefore, I need to somehow access the DataGrid, is that possible?
Simplified Style for the CustomControl (DataGridCustomControl)
<Style TargetType="{x:Type local:DataGridCustomControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DataGridCustomControl}">
<DataGrid x:Name="part_datagrid" ItemsSource ="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType={x:Type local:DataGridCustomControl}}}"
<!-- some stuff which is always the same included here -->
</DataGrid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
What I would like to do now is trying to change the properties of the datagrid in another Style. Essentially, something like shown below, which I could not get to work. (DataGridCellStyle1 not included here for abbreviation).
<Style x:Key="DataGridCustomControl1" TargetType="{x:Type local:DataGridCustomControl}" BasedOn="{StaticResource {x:Type local:DataGridCustomControl}}">
<Setter Property="DataGridCellStyle" Value="{StaticResource DataGridCellStyle1}"/>
</Style>
I actually don't have a clue if this may be achievable via ControlTemplates, but I wasn't able to get it on my own. So right now I'm not even sure, it is possible to access my part_datagrid
.
<Style x:Key="DataGridCustomControl1" TargetType="{x:Type local:DataGridCustomControl}" BasedOn="{StaticResource {x:Type local:DataGridCustomControl}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<!-- Implementation missing-->
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Add a DataGridCellStyle
dependency property of type Style
to your DataGridCustomControl
class and bind to it in the ControlTemplate
:
<ControlTemplate TargetType="{x:Type local:DataGridCustomControl}">
<DataGrid x:Name="part_datagrid" CellStyle="{TemplateBinding DataGridCellStyle}"
ItemsSource ="...">
<!-- some stuff which is always the same included here -->
</DataGrid>
</ControlTemplate>
You can then set the DataGridCellStyle
using a style setter, just like you would set any other dependency property.