wpf - 为什么要在xaml,WPF的样式中定义模板?

标签 wpf templates xaml styles

自从我开始使用MS的控件模板示例作为构建自定义控件的基础以来,我一直在想这个问题。

以“标签”示例为例:http://msdn.microsoft.com/en-us/library/ms752327.aspx

为什么在地球上这样定义:

<Style x:Key="{x:Type Label}" TargetType="Label">
  <Setter Property="HorizontalContentAlignment" Value="Left" />
  <Setter Property="VerticalContentAlignment" Value="Top" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="Label">
        <Border>
          <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                            RecognizesAccessKey="True" />
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Foreground">
              <Setter.Value>
                <SolidColorBrush Color="{DynamicResource DisabledForegroundColor}" />
              </Setter.Value>
            </Setter>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

而不是直接像这样:
<ControlTemplate x:Key="{x:Type Label}" TargetType="Label">
    <Border>
      <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                        RecognizesAccessKey="True" />
    </Border>
    <ControlTemplate.Triggers>
      <Trigger Property="IsEnabled" Value="false">
        <Setter Property="Foreground">
          <Setter.Value>
            <SolidColorBrush Color="{DynamicResource DisabledForegroundColor}" />
          </Setter.Value>
        </Setter>
      </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

然后直接而不是通过style属性作为模板调用?

我看不到这样做的隐性原因吗?还是仅仅是做事的一种方式而已?

(注意:不要告诉我这是因为水平和垂直对齐 setter !我们都知道这些是标签的默认值,如果保留这些值,这基本上是没有用的)

最佳答案

如果不使用样式,则无法将模板自动分配给特定控件类型的所有实例。为控件模板设置x:Key="{x:Type Label}"不会自动将此模板应用于所有Label类型的控件。

您可以通过将TargetType设置为Button来将样式应用于视觉树中声明下方的所有按钮,但是如果不将其包装在具有针对该样式的Setter的Style中,则无法对模板进行相同的处理。模板。

另外,请注意,在您的示例中,您可以交换

<Style x:Key="{x:Type Label}" TargetType="Label">


<Style TargetType="Label">

如果省略x:Key定义,则将TargetType设置为x:Key

关于wpf - 为什么要在xaml,WPF的样式中定义模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4872530/

相关文章:

c# - WPF 生成的文件无法编译

wpf - wpf 应用程序中的多个 Storyboard

c++ - g++ 模板错误 Small_size

c++ - 如何确定一个类是否包含子类/类型?

c# - 检查数据绑定(bind)是否存在

wpf - 是否可以仅使用 XAML 触发器单击按钮来永久更改图像的源?

C++ 模板类 : No instance of constructor matches the argument list

windows-phone-7 - 如何使用数据绑定(bind) MVVM 设置列表选择器的 selectedItem

wpf - 错误 : This PlotModel is already in use by some other PlotView control

c# - 如何在 ListView 元素中显示图像?