您能告诉我 Style 和 ControlTemplate 之间的主要区别是什么吗? 何时或为何使用其中一个?
在我看来,它们完全相同。因为我是初学者,所以我认为我错了,所以我的问题。
最佳答案
在样式中,您可以设置控件的属性。
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Red"/>
</Style>
<Button Style="{StaticResource MyButtonStyle}"/>
所有使用此样式的按钮都将其背景设置为红色。
在模板中定义控件的 UI(结构)。
<ControlTemplate x:Key="MyButtonTemplate" TargetType="Button">
<Grid>
<Rectangle Fill="Green"/>
<ContentPresenter/>
</Grid>
</ControlTemplate>
<Button Template="{StaticResource MyButtonTemplate}"/>
所有使用此模板的按钮都将具有无法更改的绿色背景。
在模板中设置的值只能通过替换整个模板来替换。 样式 中的值可以通过在使用控件时显式设置值来替换。这就是为什么最好通过使用 TemplateBinding 而不是编码值来使用控件的属性。
<ControlTemplate x:Key="MyButtonTemplate" TargetType="Button">
<Grid>
<Rectangle Fill="{TemplateBinding Background}"/>
<ContentPresenter/>
</Grid>
</ControlTemplate>
现在模板使用应用它的按钮的 Background 属性的值,因此可以自定义:
<Button Template="{StaticResource MyButtonTemplate}" Background="Yellow"/>
另一个有用的特性是控件可以选择默认样式,而无需为它们分配特定样式。你不能用模板来做到这一点。
只需删除样式的 x:Key 属性(同样:您不能使用模板执行此操作)。样式下方可视化树中的所有按钮都将应用此样式。
组合模板和样式非常强大:您可以在样式中设置模板属性:
<Style TargetType="Button">
<Setter Property="Background" Value="Red"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle Fill="{TemplateBinding Background}"/>
<ContentPresenter/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
关于c# - Style 和 ControlTemplate 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6136200/