【发布时间】:2016-09-26 08:57:19
【问题描述】:
我正在开发一个从标准 WPF DataGrid 派生的自定义 DataGrid 控件,以根据一些特定于客户端的需求对其进行扩展。
我的.cs 文件的片段:
public class DataGrid : System.Windows.Controls.DataGrid
{
#region Constructor
static DataGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DataGrid),
new FrameworkPropertyMetadata(typeof(DataGrid)));
}
}
我的.xaml 文件的片段:
<Style TargetType="local:DataGrid"
BasedOn="{StaticResource ResourceKey={x:Type DataGrid}}">
通过不在Style 标记上使用x:Key,我将此样式声明为控件的默认样式。这符合我的预期。
我不明白我如何正确声明 DataGrid 使用的子控件的默认样式,例如 DataGridRow、DataGridColumn 或 DataGridColumnHeader。
一种方法是像这样声明它......
<Style TargetType="{x:Type DataGridRow}">
...并明确设置我的local:DataGrid 的CellStyle(否则由于某种原因它仍然使用标准的WPF 样式(?))
<Setter Property="CellStyle" Value="{StaticResource {x:Type DataGridCell}}"/>
当客户在本地使用这个自定义的DataGrid时,他们可以通过简单地引用{x:Type DataGridCell}来修改样式,我觉得这很优雅:
<local:DataGrid>
<lolcal:DataGrid.CellStyle>
<Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
将其声明为默认样式的缺点是,当客户端使用标准 WPF DataGrid 时,默认样式会被我的自定义 DataGrid 覆盖。
另一种方法是在指定我的DataGridCell 样式时使用x:Key 属性...
<Style x:Key="DataGridCellStyleKey" TargetType="{x:Type DataGridCell}">
...并将我的local:DataGrid 的CellStyle 设置为此密钥
<Setter Property="CellStyle" Value="{StaticResource {x:Type DataGridCell}}" />
这样我不会覆盖默认样式,但是当我的客户想要在本地修改 CellStyle 时,他们需要明确引用 x:Key:
<local:DataGrid>
<local:DataGrid.CellStyle>
<Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridCellStyleKey}">
出于简单性和可维护性的原因,我想避免他们引用x:Key。
我正在寻找一种结合两种解决方案的最佳方式的方法:将Row/CellStyles 设置为默认样式,以避免需要引用硬编码的x:Key 字符串,同时也避免覆盖标准的默认样式WPFDataGrid。我能想到的唯一其他解决方案是为DataGridCell 和其他子控件使用自定义控件。这是一个可行的解决方案吗?
【问题讨论】:
标签: c# wpf datagrid wpf-controls wpf-style