Share via


How to: Change Border Properties

This example shows how to change the Background color of a Border element.

Example

The following example places a Button element near the center of a Canvas. The Canvas is nested within a Border element in order to display a border around the element. When you click the Button element, the Brush color of the Border element changes to LightSteelBlue. The click event also adds a string of text in a TextBlock to the Canvas (which indicates that the event occurred) and updates the text content of the Button element.

<Window
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="Border_change_programmatic.Window1"
  Title="Change Border Programmatically">
  <Border Name="root"
          BorderThickness="2"
            BorderBrush="Black"
            Background="LightGray"
            Width="350"
            Height="350">
    <Canvas>
      <Button Name="btn" Canvas.Top="40" Canvas.Left="40" Background="LightSkyBlue" Height="35" Click="ChangeBG">Click Me to change the Background Color</Button>
      <TextBlock Canvas.Top="130" Canvas.Left="40" Name="Text1">Waiting for Click!</TextBlock>
    </Canvas>
  </Border>
</Window>

The following code-behind file handles the ChangeBG method.

void ChangeBG(object sender, System.Windows.RoutedEventArgs e)   
    {
    root.Background = System.Windows.Media.Brushes.LightSteelBlue;
    btn.Content = "Clicked!";
    Text1.Text = "The background is now LightSteelBlue"; 
    }
Sub ChangeBG(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
root.Background = System.Windows.Media.Brushes.LightSteelBlue    
btn.Content = "Clicked!"
Text1.Text = "The background is now LightSteelBlue"
End Sub

See Also

Reference

Border

Concepts

Panels Overview