首页 > 解决方案 > WPF CustomControl 样式中的子项更改?

问题描述

我有一个 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>

标签: wpfcustom-controlscontroltemplate

解决方案


将类型的DataGridCellStyle 依赖属性添加Style到您的DataGridCustomControl类并在以下位置绑定到它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>

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


推荐阅读