我有
<!-- DERIVED1 - DERIVES FROM 'MOST BASE' -->
<ControlTemplate TargetType="ContentControl" x:Key="Derived1WidgetControlTemplate">
<GroupBox Style="{StaticResource WidgetControlTemplateStyle}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction Command="{Binding ExpandCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DockPanel>
<!-- Some additional controls go here ... -->
<Label Content="Blah blah" />
<DockPanel>
<!-- Content ... -->
<ContentPresenter />
</DockPanel>
</DockPanel>
</GroupBox>
</ControlTemplate>
<!-- MOST BASE -->
<ControlTemplate TargetType="ContentControl" x:Key="WidgetControlTemplate">
<GroupBox Style="{StaticResource WidgetControlTemplateStyle}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction Command="{Binding ExpandCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DockPanel>
<!-- Content ... -->
<ContentPresenter />
</DockPanel>
</GroupBox>
</ControlTemplate>
显然这两个模板几乎完全相同。我该怎么做才能摆脱重复的碎片?
将它们合并为单个ControlTemplate
并传递依赖项或附加属性不是一种选择 - 我需要有两个可区分的控制模板。
答案 0 :(得分:0)
与Style不同,不能“覆盖”ControlTemplate的一部分或基于另一个ControlTemplate的ControlTemplate。您必须(重新)将整个模板定义为一个整体。
您可以做的是将GroupBox和模板的所有常用部分移动到UserControl,并在两个模板中包含此UserControl,例如:
<UserControl x:Class="WpfApplication2.GroupBoxUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication2"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<GroupBox Style="{StaticResource WidgetControlTemplateStyle}">
<ContentPresenter />
</GroupBox>
</ControlTemplate>
</UserControl.Template>
</UserControl>
...
<ControlTemplate TargetType="ContentControl" x:Key="TemplateA">
<local:GroupBoxUserControl>
<TextBlock>1</TextBlock>
</local:GroupBoxUserControl>
</ControlTemplate>
<ControlTemplate TargetType="ContentControl" x:Key="TemplateB">
<local:GroupBoxUserControl>
<TextBlock>2</TextBlock>
</local:GroupBoxUserControl>
</ControlTemplate>
除此之外,我无法避免在XAML标记中两次声明相同的元素。恐惧。