2015-05-27 135 views
5

我正在設計一個帶有圓角平面按鈕的WPF UI。我爲這種按鈕編寫了以下代碼:WPF中的圓角平面按鈕

<Border BorderThickness="1" 
     BorderBrush="Transparent" 
     Background="DarkCyan" 
     CornerRadius="4" 
     Height="35" 
     Width="75"> 
      <Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" 
        Content="Enter" 
        VerticalAlignment="Stretch" 
        HorizontalAlignment="Stretch" 
        Background="DarkCyan" 
        Foreground="White"/> 
</Border> 

此按鈕的樣式正是我所需要的。但是在運行時,當鼠標移動到按鈕時,它不會被舍入。它是一個大小相同的矩形。實際上,按鈕會溢出邊界。因此,我增加padding邊境這樣的:

<Border BorderThickness="1" 
     BorderBrush="Transparent" 
     Background="DarkCyan" 
     CornerRadius="4" 
     Height="35" 
     Width="75" 
     Padding="2"> 
      <Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" 
        Content="Enter" 
        VerticalAlignment="Stretch" 
        HorizontalAlignment="Stretch" 
        Background="DarkCyan" 
        Foreground="White"/> 
</Border> 

在這種情況下,在hoover mode按鈕不溢出邊界了,但它仍然是矩形等按鈕’的顏色(在hoover mode)在這個矩形的區別和其他邊界的空間。所以不幸的是它還沒有用。

現在我的問題是:有沒有辦法建立一個角落,圓潤扁平按鈕(就像我提到的),在移動到按鈕便可完全圓潤的邊角空間打上空間?

+0

[WPF按鈕樣式觸發器]的可能重複(http://stackoverflow.com/questions/10777423/wpf-button-styling-trigger) – Clint

+0

不是嚴格意義上1 :1重複,但你需要的是重寫按鈕的懸停風格。 – Clint

回答

8

這可能是下降到VisualStateManager的按鈕,當鼠標懸停在按鈕上方時,該按鈕正在改變樣式。我會建議使用Style來代替。

<Style TargetType="Button" x:Key="FlatButtonStyle> 
    <Setter Property="Background" Value="DarkCyan"/> 
    <Setter Property="Foreground" Value="White"/> 
    <Setter Property="Width" Value="75"/> 
    <Setter Property="Height" Value="35"/> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="Button"> 
       <Border BorderThickness="0" 
         Background="{TemplateBinding Background}" 
         CornerRadius="4"> 
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

用法:

<Button Style="{StaticResource FlatButtonStyle}" ... /> 
+1

不好意思,但我對WPF很陌生(我今天就開始了)。你能告訴我我應該在哪裏寫樣式嗎? – parseh

+0

您可以將它們寫入Window/Parent Element的'Resources'元素中。檢查[this](http://www.wpf-tutorial.com/wpf-application/resources/)。 –

+0

沒有完美的解決方案。它顯示錯誤,我在X:鍵「‘關鍵IDictionary的’屬性只能包含在一個元素上使用‘’在上頭。」 –