2016-01-13 110 views
1

我有一个简单的问题。我已经实现了按钮样式。它基本上可以工作。这里是代码(完整的例子:你可以复制和粘贴,它会工作):WPF中按钮的实现风格

<Window x:Class="TestWPFApplication.Window5" 
     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:TestWPFApplication" 
     mc:Ignorable="d" 
     Title="Window5" Height="300" Width="300"> 
    <Window.Resources> 
     <Style TargetType="{x:Type Button}" x:Key="AButton"> 
      <Setter Property="Width" Value="120"></Setter> 
      <Setter Property="Height" Value="50"></Setter> 
      <Setter Property="Background" Value="DarkGreen" /> 
      <Setter Property="Foreground" Value="LightGreen" /> 
      <Setter Property="FontSize" Value="22" /> 
      <Setter Property="FontWeight" Value="Light" /> 
      <Setter Property="SnapsToDevicePixels" Value="True" /> 

      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="{x:Type Button}"> 
         <Border CornerRadius="15" Background="{TemplateBinding Background}"> 
          <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" 
               HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" /> 
         </Border> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </Window.Resources> 
    <Grid> 
     <Button x:Name="QuitButton" Style="{StaticResource AButton}" Content="Quit" /> 
    </Grid> 
</Window> 

这一切都很好。按钮看起来是这样的:

enter image description here

如果我的按钮稍微移动,并且Margin属性会自动生成,这...

<Button x:Name="QuitButton" Style="{StaticResource AButton}" Content="Quit" Margin="88,114,87,108.5" /> 

..按钮看起来就像这样:

enter image description here

按钮的右侧和底侧已被切断。不知道为什么:/ 问题是:任何人都可以解释我这个吗?提前致谢!

+0

尝试从ContentPresenter中删除'Margin =“0,0,0,0”'并查看是否可以帮助您 –

+0

@MohitShrivastava感谢您的关注,但它没有帮助:/ – tobiasznowak

+1

永远不要浪费你的时间使用表单设计器来定位事物。它总是把它拧紧。我认为问题在于,包含该按钮的网格没有被放大以在该新位置为该按钮腾出空间。删除它添加到按钮上的损坏的保证金值,并通过其他方式进行定位。网格行/列,StackPanel中,WrapPanel,的Horizo​​ntalAlignment等 –

回答

1

你已经设置的上边距114和下边距108.5共计225.5,但你还设置了总窗口的高度为300。只剩下77.5像素的标题栏,顶部底部窗口边框和按钮(您已将其设置为120像素高)。 WPF做出一切合适的唯一方法就是裁剪按钮。 (同样的事情发生在X轴上)。

设置您的主窗口上的WindowStyle="None"ResizeMode="NoResize",您会看到按钮现在有足够的空间可以画好。更好的是,将右边距和底边距值设置为0,现在可以将左边和上边设置为任何你想要的。

+0

其实,这是114 + 108.5 + 50(按钮的唤起注意)=>留下27,5为窗口标题栏。而我只是检查按钮在我的键盘上点击了箭头 - >这个边界道具是由VS自动生成的。为什么这么糟糕? 'WindowStyle =“无”'删除窗口的标题,它的作品。但我想要这个标题... – tobiasznowak

+1

在这种情况下,使用我的第二个解决方案。如果你想看看所有的边框等来自哪里,添加一个按钮处理程序,在那里放置一个断点,运行你的应用程序,然后单击按钮,使它到达断点。在调试器观察窗口中输入“this”并点击右边的小放大镜。这将调出WPF Tree Visualizer,它将允许您沿着树走过所有呈现的元素以及每个元素的属性(包括大小)。 –