如何在WPF中设置按钮的背景颜色

时间:2016-03-28 11:36:48

标签: c# wpf button background

您好我想在运行时更改Button Onclick事件的背景颜色。

<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>

如何获取Background的属性以在运行时设置它。

2 个答案:

答案 0 :(得分:3)

您可以处理Button的Click事件。当您单击时,以下代码将在红色和默认值之间切换背景颜色:

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

    </Button>

这是逻辑:

  

private void Button_Click_3(object sender,RoutedEventArgs e)

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

或者如果你想在Style中进行,你应该使用EventSetter:

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

答案 1 :(得分:1)

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