WPF CustomControl 样式中子项的更改?

Change of subitem in WPF CustomControl Style?

我有一个 CustomControl,其中包含一个 DataGrid。有一次我使用这个 CustomControl,我需要对 DataGrid CellStyle 的外观做一点小改动。

我现在正在做的是在 XAML 中复制我的整个 CustomControl 样式,只是为了更改 CellStyle。所以我想保留我的基本单元格样式,只覆盖 DataGrid CellStyle。因此,我需要以某种方式访问​​ DataGrid,这可能吗?

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>

我现在想做的是尝试以另一种样式更改数据网格的属性。本质上,如下所示,我无法开始工作。 (此处省略 DataGridCellStyle1)。

<Style x:Key="DataGridCustomControl1"  TargetType="{x:Type local:DataGridCustomControl}" BasedOn="{StaticResource {x:Type local:DataGridCustomControl}}">
    <Setter Property="DataGridCellStyle" Value="{StaticResource DataGridCellStyle1}"/>
</Style>

我实际上不知道这是否可以通过 ControlTemplates 实现,但我无法自己获得它。所以现在我什至不确定是否可以访问我的 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>

Style 类型的 DataGridCellStyle dependency property 添加到您的 DataGridCustomControl class 并在 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>

然后您可以使用样式 setter 设置 DataGridCellStyle,就像设置任何其他依赖项一样 属性。