在 XAML 中更改 BorderThickness

Change BorderThickness in XAML

我是 WPF 新手,XAML我正在尝试创建自定义按钮样式。

我已经有按钮模板了:

<Style x:Key="RoundButtonTemplate" TargetType="Button">
    <Setter Property="Background" Value="LightBlue"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border x:Name="Test" CornerRadius="5" Background="{TemplateBinding Background}"
                            BorderThickness="1" BorderBrush="Blue">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
                    </ContentPresenter>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

还有一个悬停在按钮上的小动画:

<Style x:Key="Animation" TargetType="Button" BasedOn="{StaticResource RoundButtonTemplate}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <ThicknessAnimation 
                            Storyboard.TargetProperty="BorderThickness"
                            Duration="0:0:0.400"
                            From="1, 1, 1, 1"
                            To="3, 3, 3, 3"/>
                        <DoubleAnimation
                            Storyboard.TargetProperty="Height"
                            Duration="0:0:0.300"
                            From="22"
                            To="25"/>
                        <DoubleAnimation
                            Storyboard.TargetProperty="Width"
                            Duration="0:0:0.300"
                            From="75"
                            To="78"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>
        </Trigger>
    </Style>

除 ThicknessAnimation 外,一切正常。它是如何工作的?

ControlTemplate 中将 BorderThickness="1" 替换为 BorderThickness="{TemplateBinding BorderThickness}"。您的 Style 动画控件 BorderThickness 未在 ControlTemplate 内部使用,因为 Border 使用固定值。

<Style x:Key="RoundButtonTemplate" TargetType="Button">
   <Setter Property="Background" Value="LightBlue"/>
   <Setter Property="BorderThickness" Value="1"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="Button">
            <Border 
               x:Name="Test" 
               CornerRadius="5" 
               Background="{TemplateBinding Background}" 
               BorderThickness="{TemplateBinding BorderThickness}" 
               BorderBrush="Blue">
               <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Border>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

您还需要添加 SetterBackground 一样的默认值。你也可以考虑用 BorderBrush 做同样的事情。它将允许您以后在不更改 Template

的情况下影响 BorderBrush 的控件