WPF按钮模板对齐未正确设置

时间:2010-05-11 23:27:50

标签: wpf xaml controltemplate

我创建了一个由边框和内容展示器组成的按钮模板。然后将样式包裹在此模板周围并应用于按钮。但是,使用此按钮时,它不携带水平和垂直对齐的值。在设计器中显示对齐并且按钮位于正确的位置,但是当我运行程序时,按钮似乎具有水平对齐=左和垂直对齐=右。任何想法?
以下是模板的代码:

<ControlTemplate TargetType="Button" x:Key="DefaultButtonTemplate">

    <Border CornerRadius="4"
            Background="{TemplateBinding Background}"
            BorderThickness="{TemplateBinding BorderThickness}"
            BorderBrush="{TemplateBinding BorderBrush}">
        <Grid>
            <ContentPresenter ContentSource="{TemplateBinding Content}" 
                    ContentTemplate="{TemplateBinding ContentTemplate}"
                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"/>
        </Grid>
    </Border>
</ControlTemplate>

以下是样式的代码:

<Style TargetType="Button">
    <Setter Property="Background" Value="{DynamicResource WindowHeaderBrush}" />
    <Setter Property="BorderBrush" Value="{DynamicResource WindowBorderBrush}" />
    <Setter Property="Template" Value="{DynamicResource DefaultButtonTemplate}" />
    <Setter Property="BorderThickness" Value="1" />
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="{DynamicResource ButtonHoverBrush}" />
            <Setter Property="BitmapEffect" Value="{DynamicResource ButtonHoverGlow}" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Background" Value="{DynamicResource ButtonPressedBrush}" />
        </Trigger>
    </Style.Triggers>
</Style>

这是按钮的代码:

<Button Name="button1" Height="31"  VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,10,10">Button</Button>

文件背后没有代码

此代码的结果是一个按钮,显示在父级平顶的左上角,与边缘对齐

1 个答案:

答案 0 :(得分:2)

我认为该行

<Button Name="button1" Height="31"  VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,10,10">Button</Button>

应该是

<Button Name="button1" Height="31"  VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" Margin="0,0,10,10">Button</Button>

或者您只是设置按钮的对齐而不是内容。