How to add a Button click event handler in WPF?

The Click attribute of the Button element adds the click event handler. The following code adds the click event handler for a Button.

<Button x:Name="DrawCircleButton" Height="40" Width="120"

        Canvas.Left="10" Canvas.Top="10"

        Content="Draw Circle"

        VerticalAlignment="Top"

        HorizontalAlignment="Left">

Click="DrawCircleButton_Click"

</Button>

The code for the click event handler looks like following.

private void DrawCircleButton_Click(object sender, RoutedEventArgs e)

{

 

}

Now, whatever code you write in the click event handler that will be executed on the Button click. The code listed in Listing 3 creates a circle on the Button click event handler.

private void DrawCircleButton_Click(object sender, RoutedEventArgs e)

{

    // creates a Circle

    Ellipse circle = new Ellipse();

    circle.Width = 200;

    circle.Height = 200;

    circle.Fill = new SolidColorBrush(Colors.Yellow);

    circle.Stroke = new SolidColorBrush(Colors.Black);

    circle.StrokeThickness = 4;

 

    LayoutRoot.Children.Add(circle);

}