按钮默认为ControlTemplate,TextElement如何在触发器中工作?

时间:2018-01-03 09:38:04

标签: c# .net wpf

我是wpf的新手,并尝试了解ControlTemplate的工作原理。

我查看Button的默认模板,即:

<?xml version="1.0" encoding="utf-16"?>
<ControlTemplate TargetType="ButtonBase" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:mwt="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero">

  <mwt:ButtonChrome Background="{TemplateBinding Panel.Background}" BorderBrush="{TemplateBinding Border.BorderBrush}" RenderDefaulted="{TemplateBinding Button.IsDefaulted}" RenderMouseOver="{TemplateBinding UIElement.IsMouseOver}" RenderPressed="{TemplateBinding ButtonBase.IsPressed}" Name="Chrome" SnapsToDevicePixels="True">
    <ContentPresenter RecognizesAccessKey="True" Content="{TemplateBinding ContentControl.Content}" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}" Margin="{TemplateBinding Control.Padding}" HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
  </mwt:ButtonChrome>

  <ControlTemplate.Triggers>
    <Trigger Property="UIElement.IsKeyboardFocused">
      <Setter Property="mwt:ButtonChrome.RenderDefaulted" TargetName="Chrome">
        <Setter.Value>
          <s:Boolean>True</s:Boolean>
        </Setter.Value>
      </Setter>
      <Trigger.Value>
        <s:Boolean>True</s:Boolean>
      </Trigger.Value>
    </Trigger>
    <Trigger Property="ToggleButton.IsChecked">
      <Setter Property="mwt:ButtonChrome.RenderPressed" TargetName="Chrome">
        <Setter.Value>
          <s:Boolean>True</s:Boolean>
        </Setter.Value>
      </Setter>
      <Trigger.Value>
        <s:Boolean>True</s:Boolean>
      </Trigger.Value>
    </Trigger>
    <Trigger Property="UIElement.IsEnabled">
      <Setter Property="TextElement.Foreground">
        <Setter.Value>
          <SolidColorBrush>#FFADADAD</SolidColorBrush>
        </Setter.Value>
      </Setter>
      <Trigger.Value>
        <s:Boolean>False</s:Boolean>
      </Trigger.Value>
    </Trigger>
  </ControlTemplate.Triggers>
</ControlTemplate>

对我来说,TemplateBindingControl / mwt:ButtonChrome / UIElement / ButtonBase看起来很有意义,它们位于{{1 }}

但这一行令我困惑,它如何与ButtonBase一起使用,因为在其模板的其他地方没有对它的定义?

TextElement

1 个答案:

答案 0 :(得分:0)

&#34; TextElement.Foreground&#34;只是一种在XAML中引用TextElement类中定义的ForegroundProperty依赖项属性的方法。在c#代码中,它可以用作TextElement.ForegroundProperty

需要更改可能出现在ContentPresenter中的文本颜色(ContentPresenter本身不具有Foreground属性)

在大多数情况下,可以省略类名,例如<Trigger Property="IsEnabled">代替<Trigger Property="UIElement.IsEnabled">,因为ButtonBase UIElementIsEnabled属性可在模板中访问