为自定义控件设置样式

3

我正尝试创建自定义用户控件。我已经创建了一个ResourceDictionary文件(Themes\Generic.xaml),其中包含两个样式:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit"
    xmlns:themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
    xmlns:components="clr-namespace:ORPO.WPF.Components">

    <Style TargetType="{x:Type components:HeaderFilterDataGrid}" BasedOn="{StaticResource {x:Type DataGrid}}">
        ...
    </Style>
    <Style TargetType="{x:Type DataGridColumnHeader}">
        ...
    </Style>
</ResourceDictionary>

我的自定义控件类:
public class HeaderFilterDataGrid : DataGrid
    {
...
static HeaderFilterDataGrid()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(HeaderFilterDataGrid),
new FrameworkPropertyMetadata(typeof(HeaderFilterDataGrid)));            
        }
...
}

当我应用第一个样式时,它能够正常工作。

DefaultStyleKeyProperty.OverrideMetadata(typeof(HeaderFilterDataGrid),
    new FrameworkPropertyMetadata(typeof(HeaderFilterDataGrid)));   

如何为我的自定义控件应用第二个样式? 我需要同时应用两种样式。

2
尝试将 DataGridColumnHeader 样式放置在 HeaderFilterDataGrid 样式的 Style.Resources 中。 - Clemens
它运行正常!谢谢你! - Stopee
1个回答

4

DataGridColumnHeader样式放置在HeaderFilterDataGrid样式的资源中。这样DataGridColumnHeader将成为HeaderFilterDataGrid中所有DataGridColumnHeader的默认样式。

<ResourceDictionary ...>
    <Style TargetType="{x:Type components:HeaderFilterDataGrid}"
           BasedOn="{StaticResource {x:Type DataGrid}}">
        <Style.Resources>
            <Style TargetType="{x:Type DataGridColumnHeader}">
            ...
            </Style>
        </Style.Resources>
        ...
    </Style>
</ResourceDictionary>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接