Изменение подраздела в стиле WPF CustomControl? - PullRequest
0 голосов
/ 07 апреля 2020

У меня есть CustomControl, который содержит среди прочего DataGrid. Однажды, когда я использую этот CustomControl, мне нужно немного изменить внешний вид DataGrid CellStyle.

Сейчас я делаю дублирование всего стиля CustomControl в XAML, чтобы изменить 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>

1 Ответ

1 голос
/ 07 апреля 2020

Добавьте 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 с использованием установщика стиля, точно так же, как вы устанавливаете любое другое свойство зависимости.

...