我正在使用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
對不對?任何其他想法?