wpf - 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>
解决方案
将类型的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
使用样式设置器来设置,就像设置任何其他依赖项属性一样。
推荐阅读
- dart - 发生更改时如何在 Flutter 中重建小部件
- node.js - 将字体添加到 Puppeteer PDF 渲染器
- c++ - 有没有办法防止 libcurl 缓冲?
- android - 在android studio中将字符串从getString转换为getBytes
- .net - 如何从 .NET 应用程序自动化 Adobe Acrobat Pro?
- r - 如何摆脱 R Shiny 文本输出中逗号前后的多余空格?
- java - 每次我添加/删除任何东西时都强制重新启动并使缓存无效?
- amazon-web-services - 在 python 中使用“aws cli”从 S3 下载多个文件
- javascript - 从另一个模块导出模块类
- javascript - 当 props 和 state 没有改变时 React PureComponent 更新