【问题标题】:Default Style of subcontrols in a custom DataGrid control自定义 DataGrid 控件中子控件的默认样式
【发布时间】: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


    【解决方案1】:

    我认为您必须在自定义 DataGrid 的默认样式范围内声明第一种方法的样式,如下所示:

    <Style TargetType="local:DataGrid" BasedOn="{StaticResource ResourceKey={x:Type DataGrid}}">
        <Setter Property="CellStyle">
            <Setter.Value>
                <Style TargetType="DataGridCell">
                    <!-- Your Default Style here -->
                </Style>
            </Setter.Value>
        </Setter>
    </Style>
    

    这不会覆盖默认的 DataGrids CellStyle,用户可以轻松更改。

    【讨论】:

    • 我刚刚尝试过,但无法弄清楚在 XAML 中创建自定义 DataGrid 时用户如何扩展我的标准样式。通过使用&lt;Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}"&gt;,它仍然引用标准的 WPF DataGrid,但我希望它们以我的自定义 DataGrid 样式为基础。
    • 有了这个,用户可以轻松地设置新的样式。使用 Cellstyle 作为基础是不可能的。通过使用 BasedOn="{StaticResource {x:Type DataGridCell}}" 您可以从类型中引用基本样式。因为您的自定义 DataGrid 没有为 DataGridCell 提供新类型,所以无法在自定义 DataGrid CellStyle 和全局样式之间做出决定(这些样式独立于 DataGrid...)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    相关资源
    最近更新 更多