【问题标题】:Set size of border inside ControlTemplate to size of button将 ControlTemplate 内的边框大小设置为按钮大小
【发布时间】:2021-04-02 08:55:46
【问题描述】:

我想要几个按钮的 ControlTemplate,这样当鼠标悬停在按钮上时我可以控制按钮的颜色。问题是我使用边框作为 ControlTemplate 内容,并且我希望该边框的大小(BorderThickness)等于按钮的大小。由于按钮是网格的一部分,它的大小是灵活的。到目前为止,这是我的代码:

<Window x:Class="WPFTesting.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WPFTesting"
    mc:Ignorable="d"
    Title="MainWindow" Height="400" Width="350">

<Window.Resources>
    <Style TargetType="Button" x:Key="ex">
        <Setter Property="Background" Value="Black"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontSize" Value="50"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border BorderBrush="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Button Content="Btn0" Margin="0, 10, 0, 30" Style="{StaticResource ex}" Grid.Row="0"/>
    <Button Content="Btn1" Margin="0, 10, 0, 30" Grid.Row="1"/>
    <Button Content="Btn2" Margin="0, 10, 0, 30" Grid.Row="2"/> 
</Grid>
如何使 BorderThickness 填充整个网格行。我是否应该首先使用边框作为 ControlTemplate 内容?

【问题讨论】:

  • 只使用边框背景:&lt;Border Background="{TemplateBinding Background}"&gt;
  • @ASh 谢谢,按钮现在大小正确,但没有显示任何内容。您对如何解决这个问题有任何想法吗?

标签: wpf xaml controltemplate wpf-style


【解决方案1】:

你应该写

<ControlTemplate TargetType="Button">
    <Border Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}">
        <ContentPresenter
            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
</ControlTemplate>

【讨论】:

  • 谢谢!这解决了按钮大小错误的问题。但是,按钮内没有显示任何内容。关于如何解决这个问题的任何想法?
  • 你错过了&lt;ControlTemplate TargetType="Button"&gt;
猜你喜欢
  • 2016-09-13
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-10
相关资源
最近更新 更多