Partager via


How to: Set the Background Property of a Button

This example shows how to set the Background property of a Button.

Example

The following markup example contains two buttons of different colors and a button labeled Reset. When a user clicks one of the colored buttons, its Background color changes to the color of the other colored button. The Reset button resets the two colored buttons to their original colors.

This example creates the buttons by using markup; however, the Click event handlers are written in code-behind.

<Button Name="btn1" Background="Pink" BorderBrush="Black" BorderThickness="1" Click="OnClick1">
        ClickMe1</Button>
<Button Name="btn2" Background="LightBlue" BorderBrush="Black" BorderThickness="1" Click="OnClick2">
        ClickMe2</Button>
<Button Name="btn3" Click="OnClick3">Reset</Button>
void OnClick1(object sender, RoutedEventArgs e)
{
    btn1.Background = Brushes.LightBlue;
}

void OnClick2(object sender, RoutedEventArgs e)
{
    btn2.Background = Brushes.Pink;
}

void OnClick3(object sender, RoutedEventArgs e)
{
    btn1.Background = Brushes.Pink;
    btn2.Background = Brushes.LightBlue;
}
Sub OnClick1(ByVal sender As Object, ByVal e As RoutedEventArgs)
    btn1.Background = Brushes.LightBlue
End Sub

Sub OnClick2(ByVal sender As Object, ByVal e As RoutedEventArgs)
    btn2.Background = Brushes.Pink
End Sub

Sub OnClick3(ByVal sender As Object, ByVal e As RoutedEventArgs)
    btn1.Background = System.Windows.Media.Brushes.Pink
    btn2.Background = System.Windows.Media.Brushes.LightBlue
End Sub

For the complete sample, see Buttons Sample.

See Also

Tasks

How to: Create a Button
How to: Create a Button That Has an Image

Reference

Background
Button

Concepts

Button Overview

Other Resources

Buttons Sample
Button How-to Topics
Button Samples