我正在使用ControlTemplate
来定义WPF应用程序中按钮的外观。此外,我想使用样式来设置我的按钮的某些方面。这些样式应该在ControlTemplate
定义,如(简化的)元件设置属性:如何使用样式更改模板化控件
<Window.Resources>
<ControlTemplate x:Key="Template1" TargetType="Button">
<Grid>
<Rectangle Name="rect" Fill="White" Stroke="Blue" StrokeThickness="2"/>
<TextBlock Name="text" Text="Hallo" Foreground="Red" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</ControlTemplate>
<Style x:Key="Style1" TargetType="Button" >
<Setter TargetName="rect" Property="Fill" Value="Red"/>
</Style>
</Window.Resources>
现在,编译器抱怨说,的TargetName“矩形”是不是一个有效目标,我可以自一个untemplatized Button
没有按”理解t包含名为“rect”的元素。
我知道我可以改变样式来设置完整的模板,但我想避免这种情况(因为模板比这里显示的要复杂得多,我不想为每种样式复制它... )
是否有可能实现此行为?也许通过设置TargetType
对不对?任何其他想法?