2016-03-28 225 views
-1

你好,我想在運行時更改我的按鈕Onclick事件的背景顏色。如何在WPF中設置按鈕的背景顏色

<Button FontStyle="Normal" FontWeight="Normal" HorizontalAlignment="Right" Margin="0,0,30,535" Name="b9" Width="96" Height="95" VerticalAlignment="Bottom" Content="9" FontFamily="Verdana" Click="Button_Click" Visibility="Visible"> 
<Button.Template> 
<ControlTemplate> 
<Rectangle Name="myRectangle" RadiusX="46.5" RadiusY="46.5" Stroke="LightYellow" StrokeThickness="3"> 
<Rectangle.Fill> 
<VisualBrush Opacity="0.7"> 
<VisualBrush.Visual> 
<TextBlock Background="Green" Foreground="LightYellow" Name="myTextBlock" Padding="10">Change Color</TextBlock> 
</VisualBrush.Visual> 
</VisualBrush> 
</Rectangle.Fill> 
</Rectangle> 
<ControlTemplate.Triggers> 
<Trigger Property="ButtonBase.IsPressed" Value="True"> 
<Setter Property="Shape.Stroke" TargetName="myRectangle" Value="LightGreen" /> 
<Setter Property="TextBlock.Background" TargetName="myTextBlock"> 
<Setter.Value> 
<LinearGradientBrush> 
<GradientStop Color="DarkGreen" Offset="1" /> 
<GradientStop Color="Green" Offset="0.5" /> 
<GradientStop Color="DarkGreen" Offset="0" /> 
</LinearGradientBrush> 
</Setter.Value> 
</Setter> 
</Trigger> 
</ControlTemplate.Triggers> 
</ControlTemplate> 
</Button.Template> 
</Button> 

我怎樣才能得到背景的屬性來設置它在運行時。

回答

1
var textBlock = (TextBlock)b9.Template.FindName("myTextBlock", b9); 
textBlock.Background = Brushes.Blue; 
3

您可以處理按鈕的Click事件。下面的代碼將切換紅色和默認的之間的背景顏色,當你點擊它:

<Button Content="test" Click="Button_Click_3"> 

    </Button> 

這裏的邏輯:

私人無效Button_Click_3(對象發件人, RoutedEventArgs E)

{ 
     Button btn = sender as Button; 
     btn.Background = btn.Background == Brushes.Red ? (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFDDDDDD")) : Brushes.Red; 
    } 

或者,如果你想要做一個風格,你應該使用一個EventSetter:

 <Button.Style> 
      <Style TargetType="Button"> 
       <EventSetter Event="Click" Handler="Button_Click_3"/> 
      </Style> 
     </Button.Style> 
    </Button>