【发布时间】:2010-08-21 15:18:47
【问题描述】:
我使用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“rect”不是我能理解的有效目标,因为未模板化的 Button 不包含名为“rect”的元素。
我知道我可以将样式更改为设置完整的模板,但我想避免这种情况(因为模板比此处显示的要复杂得多,我不想为每种样式复制它...)
是否有可能实现这种行为?也许通过设置TargetType 对吗?还有其他想法吗?
【问题讨论】: