我目前正在尝试弄清楚如何在其他控件模板中重用模板(如标题所示)。我想做的是制作一堆按钮,它们都略有不同,但有几个相似的功能。它们都共享几个相同的图形元素,并具有处理这些图形元素的相同触发器。我希望做的是能够将该代码取出并将其放入另一个模板中,并且只需让所有按钮都引用该模板。这样一来,管理起来更容易,整体上也更有意义。我确信有一种方法,但我对 WPF 还是很陌生。谢谢你的帮助!
编辑:这是一些显示我想要做的代码。
<ControlTemplate x:Key="LeftJustifyButtonTemplate" TargetType="{x:Type RadioButton}">
<Grid Width="24" Height="24">
<Rectangle HorizontalAlignment="Stretch" Fill="#00000000" Stroke="{x:Null}"/>
<Rectangle x:Name="backRectangle" HorizontalAlignment="Stretch" Margin="0,0,0,0" Stroke="#FFB9B9B9" StrokeThickness="0.5" RadiusX="4" RadiusY="4" Visibility="Hidden">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.146,0.146" StartPoint="2.057,2.057">
<GradientStop Color="#FF000000" Offset="0"/>
<GradientStop Color="#FFFFFFFF" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Rectangle x:Name="foreRectangle" Margin="1,1,1,1" VerticalAlignment="Stretch" Fill="#FFE0E0E0" Stroke="{x:Null}" StrokeThickness="0.5" RadiusX="4" RadiusY="4" Visibility="Hidden"/>
<Path Margin="2.875,7,2.875,0" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M2.875,7.5 L21.145964,7.5" VerticalAlignment="Top" Height="1" StrokeThickness="0.5"/>
<Path Margin="2.875,9.375,8,0" VerticalAlignment="Top" Height="1" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M3.625,4 L17.514069,4" StrokeThickness="0.5"/>
<Path Margin="2.875,11.5,2.875,11.5" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M2.875,7.5 L21.145964,7.5" StrokeThickness="0.5"/>
<Path Margin="2.875,0,8,9.375" VerticalAlignment="Bottom" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M3.625,4 L17.514069,4" Height="1" StrokeThickness="0.5"/>
<Path Margin="2.875,0,2.875,7" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Data="M2.875,7.5 L21.145964,7.5" VerticalAlignment="Bottom" Height="1" StrokeThickness="0.5"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="backRectangle" Property="Visibility" Value="Visible"/>
<Setter TargetName="foreRectangle" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="backRectangle" Property="Visibility" Value="Visible"/>
<Setter TargetName="foreRectangle" Property="Visibility" Value="Visible"/>
<Setter TargetName="foreRectangle" Property="Fill" Value="#FFFFFFFF"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
除了中间的 5 个路径之外,几乎所有这些都用于几个按钮。这是因为它用于鼠标悬停和检查触发器。我想要做的是能够将所有代码放在一个地方,然后让几个按钮能够引用该代码。