c# - Style 和 ControlTemplate 的区别

标签 c# .net wpf xaml

您能告诉我 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/

相关文章:

c# - (新格式)visual studio 项目中的可选 appsettings.local.json

c# - 如何通过 app.config 变量覆盖 settings.settings 变量

c# - C#If…Else比较字符串值与类型

c# - 如何使用具有负载平衡和有限并行度的任务并行库 (TPL)?

wpf - 我可以从工作线程初始化 ViewModel 吗?

c# - Matrix 4x4 对象的结构或类

c# - 如何在 C# 中将字符串转换为具有两位小数的货币?

c# - 为什么 DbConnection.OpenAsync(CancellationToken) 的默认实现是同步的?

wpf - 动态改变 FocusManager.FocusedElement

WPF 组合框自动完成/智能感知区分大小写