是否可以告诉控件模板资源仅将自身应用于继承的控件?



我正在使用DevExpress GridControl,我从中继承了一个类。 该类只是 C# 中的一个类,它添加了一些依赖项属性,它没有 XAML 页。

在我的ResourceDictionary中,我定义了两个元素:一个ControlTemplate,用于向网格的搜索控件添加一些按钮,以及一个Style用于调整该搜索控件的边距/填充属性。 这些使用Key标识符,使它们适用于我使用的每个网格。 但我真的只希望它们在网格属于我继承类型时应用。

如何使这两个元素仅应用于继承的控件,而不应用于基本网格控件?

当前顶级标签定义:

<ControlTemplate x:Key="{dxet:SearchControlThemeKey ResourceKey=Template, ThemeName=MyTheme}">
<Style x:Key="{dxgt:TableViewThemeKey ThemeName=MyTheme, ResourceKey=SearchPanelContentTemplate}"
TargetType="{x:Type ContentControl}">

其中dxetdxgt是 DevExpress 命名空间。

最直接的解决方案可能是在自定义网格控件的默认Style中声明这些资源:

<Style TargetType="local:MyGridControl"
BasedOn="{x:Static dxg:GridControl}">
<!-- TODO: Double check the BasedOn style key above. -->
<!-- Put any *new* setters, triggers, etc. here. -->
<!-- You'll already inherit the setters and triggers from the BasedOn style. -->
<Style.Resources>
<!-- Resources only visible in the context of your custom grid's style: -->
<ControlTemplate x:Key="{dxet:SearchControlThemeKey ResourceKey=Template, ThemeName=MyTheme}" />
<Style x:Key="{dxgt:TableViewThemeKey ThemeName=MyTheme, ResourceKey=SearchPanelContentTemplate}"
TargetType="{x:Type ContentControl}" />
</Style.Resources>
</Style>

将上述样式放在Themes\Generic.xaml资源字典中,该字典位于声明自定义网格控件的同一程序集中。 这是 WPF 将探测默认控件样式的标准位置。 如果您的AssemblyInfo.cs尚未包含此类条目,请添加以下内容:

[assembly: ThemeInfo(
// Where theme specific resource dictionaries are located
// (used if a resource is not found in the page, or application
// resource dictionaries)
ResourceDictionaryLocation.None,
// Where the generic resource dictionary is located
// (used if a resource is not found in the page, app, or 
// any theme specific resource dictionaries)                                 
ResourceDictionaryLocation.SourceAssembly 
)]

结果应该是自定义网格的实例将看到被覆盖的资源,但标准GridControl的实例将看到默认版本。

确保覆盖自定义网格的默认样式键:

static MyGridControl()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(MyGridControl),
new FrameworkPropertyMetadata(typeof(MyGridControl)));
}

备选提案

您是否考虑过使用附加的依赖项属性向现有网格控件添加新功能,而不是使用您自己的子类对其进行扩展?

根据您正在执行的所有操作,最好声明一个GridExtensions类,该类为自定义按钮注册一些附加属性、路由事件和类级命令处理程序。

最新更新