WPF Button

Introduction
 

This article demonstrates how to the WPF Button control using XAML and C#. The article starts with the introduction of XAML Button element and its properties followed by the positioning, styling, and formatting of the control. The article also shows how to use the Button control events.
 
Creating a Button
 

The Button XAML element represents a WPF Button control. 

  1. <Button/> 
The Width and Height attributes of the Button element represent the width and the height of a Button. The Content property of the Button element sets the text of a button. The x:Name attribute represents the name of the control, which is a unique identifier of a control. You may also use the Name property to set the name of a control.
 
The code snippet in Listing 1 creates a Button control and sets the name, height, width, and content of a Button control. 
  1. <Button x:Name="DrawCircleButton" Height="40" Width="120"   
  2. Content="Draw Circle" >  
  3. </Button> 
Listing 1
 
The default property of a button is Content.
 
The code snippet in Listing 2 creates the same button as created by Listing 1.
  1. <Button x:Name="DrawCircleButton" Height="40" Width="120" >  
  2. Draw Circle  
  3. </Button> 
Listing 2
 
The output looks like Figure 1.
 
Creating a Button in WPF

Figure 1
 
Positioning a Button
 

If you place a button on a Grid control, the button will be placed in the center of Grid. If you are using a Canvas as your parent control of Button, the Button will be placed in the left top corner of Canvas.
 
You can use Margin property to position a button control in a container like a Grid. The Margin property takes 4 values that represents left, top, right, and bottom positions. Listing 3 sets the Margin property of the Button control. 
  1. <Button x:Name="DrawCircleButton" Content="Draw Circle"   
  2. Margin="60,120,80,120" /> 
Listing 3
 
The position of the Button control set in Listing 3 generates Figure 2.
 
Positioning a Button in WPF

Figure 2
 
If you are using a Canvas, you may also use Canvas.Left and Canvas.Top properties.
 
You may also use VerticalAlignment and HorizontalAlignment attributes to set vertical alignment, and horizontal alignment of a button.
 
The code snippet in Listing 4 sets the position of the Button control to the left top corner of the Canvas. 
  1. <Button x:Name="DrawCircleButton" Height="40" Width="120"   
  2.     Canvas.Left="10" Canvas.Top="10"   
  3.     Content="Draw Circle"  
  4.     VerticalAlignment="Top"   
  5.     HorizontalAlignment="Left">  
  6. </Button> 
Listing 4

Formatting a Button

Not let’s get a little creative. How about we create a Button control with a border formatting, background, and foreground of the Button?

The BorderBrush property of the Button sets a brush to draw the border of a Button. You may use any brush to fill the border. The following code snippet uses a linear gradient brush to draw the border with a combination of red and blue color.
  1. <Button.BorderBrush>  
  2.     <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
  3.         <GradientStop Color="Blue" Offset="0" />  
  4.         <GradientStop Color="Red" Offset="1.0" />  
  5.     </LinearGradientBrush>  
  6. </Button.BorderBrush> 
Listing 5

The Background and Foreground properties of the Button set the background and foreground colors of a Button. You may use any brush to fill the border. The following code snippet uses linear gradient brushes to draw the background and foreground of a Button. 
  1. <Button.Background>  
  2.     <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
  3.         <GradientStop Color="Blue" Offset="0.1" />  
  4.         <GradientStop Color="Orange" Offset="0.25" />   
  5.         <GradientStop Color="Green" Offset="0.75" />  
  6.         <GradientStop Color="Red" Offset="1.0" />  
  7.     </LinearGradientBrush>  
  8. </Button.Background>  
  9. <Button.Foreground>  
  10.     <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >   
  11.         <GradientStop Color="Orange" Offset="0.25" />  
  12.         <GradientStop Color="Green" Offset="1.0" />   
  13.     </LinearGradientBrush>  
  14. </Button.Foreground> 
Listing 6

The final complete source code looks like this.
  1. <Window x:Class="ButtonSample.Window1"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     Title="Window1" Height="300" Width="300">  
  5.     <Canvas Name="LayoutRoot">  
  6.         <Button x:Name="DrawCircleButton" Height="40" Width="120"   
  7.             Canvas.Left="10" Canvas.Top="10" Click="DrawCircleButton_Click" >  
  8.   
  9.             <Button.BorderBrush>  
  10.                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
  11.                     <GradientStop Color="Blue" Offset="0" />  
  12.                     <GradientStop Color="Red" Offset="1.0" />  
  13.                 </LinearGradientBrush>  
  14.             </Button.BorderBrush>  
  15.             <Button.Background>  
  16.                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
  17.                     <GradientStop Color="Blue" Offset="0.1" />  
  18.                    <GradientStop Color="Orange" Offset="0.25" />  
  19.                    <GradientStop Color="White" Offset="0.75" />  
  20.                     <GradientStop Color="Red" Offset="1.0" />  
  21.                 </LinearGradientBrush>  
  22.             </Button.Background>  
  23.             <Button.Foreground>  
  24.                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >  
  25.                     <GradientStop Color="Black" Offset="0.25" />  
  26.                     <GradientStop Color="Green" Offset="1.0" />  
  27.                 </LinearGradientBrush>  
  28.             </Button.Foreground>  
  29.             Draw Circle  
  30.         </Button>  
  31.     </Canvas>  
  32. </Window> 
Listing 7
 
The new Button looks like below:
 
Formatting a Button in WPF

Figure 3
 
Creating a Button Dynamically
 

The code listed in Listing 8 creates a Button control programmatically. First, it creates a Button object and sets its width, height, contents, background and foreground and later the Button is added to the LayoutRoot. 
  1. private void CreateAButton()  
  2. {  
  3.     Button btn = new Button();  
  4.     btn.Height = 80;  
  5.     btn.Width = 150;  
  6.     btn.Content = "Click ME";  
  7.     btn.Background = new SolidColorBrush(Colors.Orange);  
  8.     btn.Foreground = new SolidColorBrush(Colors.Black);  
  9.     LayoutRoot.Children.Add(btn);  

Listing 8

Button Content
 
Each XAML object element is capable of displaying different content types. XAML provides a special property called Content that works to display the content of the element depending on the element capabilities. For example, a Content property of a Button can be a set to a string, an object, a UIElement, or even and container. However, the Content property of a ListBox is set using the Items property.
 
Note: Some XAML object elements may not have the Content property available directly. It must be set through a property.

The code snippet in Listing 9 creates a Button control and sets its Content property to a string “Hello XAML”. The output looks like Figure 10.
  1. <Button Height="50" Margin="10,10,350,310" Content="Hello XAML" /> 
Listing 9

Listing 10 is an alternative way to set the Content property of a Button.
  1. <Button Height="50" Margin="10,10,350,310">Hello XAML</Button> 
Listing 10

The output of Listing 10 looks like same as Figure 4.
 
Button Content

Figure 4

A Button element can display other child elements as its content. The code listed in Listing 11 sets a Rectangle element as the content of the Button.
  1. <Button Height="80" Margin="10,80,300,170">  
  2.     <Rectangle Height="60" Width="120" Fill="Green"/>  
  3. </Button> 
Listing 11
 
The output of Listing 20 looks like same as Figure 5.

Edit in Button
Figure 5

Content property can also be a container or a parent element hosting child elements. The code listed in Listing 12 sets a StackPanel container with 5 child elements as the content of the Button.
  1. <Button Margin="10,201,100,40">  
  2.     <StackPanel Orientation="Horizontal">  
  3.         <Ellipse Height="60" Width="60" Fill="Red"/>  
  4.         <TextBlock TextAlignment="Center"><Run Text=" Red Circle"/></TextBlock>  
  5.         <TextBlock TextAlignment="Center"><Run Text=" "/></TextBlock>  
  6.         <Rectangle Height="60" Width="120" Fill="Green"></Rectangle>  
  7.         <TextBlock TextAlignment="Center"><Run Text=" Green Rectangle"/></TextBlock>  
  8.     </StackPanel>  
  9. </Button> 
Listing 12
 
The output of Listing 12 looks like same as Figure 6.
 
Coluring in Button
Figure 6
 
The final XAML code is listed in Listing 13. 
  1. <Window x:Class="ContentPropertySample.MainWindow"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     Title="MainWindow" Height="400" Width="500" >  
  5.     <Grid x:Name="ParentGrid">  
  6.         <Button Height="50" Margin="10,10,350,310" Content="Hello XAML" />  
  7.         <Button Height="80" Margin="10,80,300,170">  
  8.             <Rectangle Height="60" Width="120" Fill="Green"></Rectangle>  
  9.         </Button>  
  10.         <Button Margin="10,201,100,40">  
  11.             <StackPanel Orientation="Horizontal">  
  12.                 <Ellipse Height="60" Width="60" Fill="Red"/>  
  13.                 <TextBlock TextAlignment="Center"><Run Text=" Red Circle"/></TextBlock>  
  14.                 <TextBlock TextAlignment="Center"><Run Text=" "/></TextBlock>  
  15.                 <Rectangle Height="60" Width="120" Fill="Green"></Rectangle>  
  16.                 <TextBlock TextAlignment="Center"><Run Text=" Green Rectangle"/></TextBlock>  
  17.             </StackPanel>  
  18.         </Button>   
  19.     </Grid>  
  20. </Window> 
Listing 13
 
The output of Listing 13 looks like same as Figure 7.
 
Final Button Content

Figure 7
 
As you can imagine from the above examples, you can pretty much host any user interfaces as content of a XAML element.
 
The code listed in Listing 14 creates the above Button controls dynamically in the code and sets their Content properties to a string, a Rectangle, and a StackPanel respectively. 
  1. // Button with string content  
  2. Button helloButton = new Button();  
  3. helloButton.Margin = new Thickness(10,10,350,310);  
  4. helloButton.Content = "Hello XAML";  
  5.    
  6. // Button with a UIElement  
  7. Button buttonWithRectangle = new Button();  
  8. buttonWithRectangle.Height = 80;  
  9. buttonWithRectangle.Margin = new Thickness(10, 80, 300, 170);  
  10. // Create a Rectangle  
  11. Rectangle greenRectangle = new Rectangle();  
  12. greenRectangle.Height = 60;  
  13. greenRectangle.Width = 120;  
  14. greenRectangle.Fill = Brushes.Green;  
  15. // Set Rectangle as Button.Content  
  16. buttonWithRectangle.Content = greenRectangle;  
  17.   
  18. // Button with a Container, StackPanel  
  19. Button buttonWithStackPanel = new Button();  
  20. buttonWithStackPanel.Margin = new Thickness(10, 10, 350, 310);  
  21. // Create a StackPanel and set its orinetation to horizontal  
  22. StackPanel stackPanel = new StackPanel();  
  23. stackPanel.Orientation = Orientation.Horizontal;  
  24. // Create an Ellipse  
  25. Ellipse redEllipse = new Ellipse();  
  26. redEllipse.Width = 60;  
  27. redEllipse.Height = 60;  
  28. redEllipse.Fill = Brushes.Red;  
  29. // Add to StackPanel  
  30. stackPanel.Children.Add(redEllipse);  
  31.   
  32. // Create a TextBlock  
  33. TextBlock textBlock1 = new TextBlock();  
  34. textBlock1.TextAlignment = TextAlignment.Left;  
  35. textBlock1.Text = "Red Circle";  
  36. // Add to StackPanel  
  37. stackPanel.Children.Add(textBlock1);  
  38.   
  39. // Create a TextBlock  
  40. extBlock space = new TextBlock();  
  41. space.TextAlignment = TextAlignment.Center;  
  42. space.Text = " ";  
  43. // Add to StackPanel  
  44. stackPanel.Children.Add(space);  
  45.   
  46. // Create a Rectangle  
  47. Rectangle greenRectangle2 = new Rectangle();  
  48. greenRectangle2.Height = 60;  
  49. greenRectangle2.Width = 120;  
  50. greenRectangle2.Fill = Brushes.Green;  
  51. // Add to StackPanel  
  52. stackPanel.Children.Add(greenRectangle2);  
  53.    
  54. // Create a TextBlock  
  55. TextBlock textBlock2 = new TextBlock();  
  56. textBlock2.TextAlignment = TextAlignment.Left;  
  57. textBlock2.Text = "Green Rectangle";  
  58. // Add to StackPanel  
  59. stackPanel.Children.Add(textBlock2);  
  60.    
  61. // Set StackPaenl as Button.Content  
  62. buttonWithStackPanel.Content = stackPanel;  
  63.    
  64. // Add dynamic button controls to the Window  
  65. ParentGrid.Children.Add(helloButton);  
  66. ParentGrid.Children.Add(buttonWithRectangle);  
  67. ParentGrid.Children.Add(buttonWithStackPanel); 
Listing 14
 
In this article, we saw the meaning of the Content property available to XAML elements and how to use in our application.
 
Setting Image as Background of a Button

To set an image as background of a Button, we can set an image as the Background of the Button. The code snippet in Listing 15 sets the background of a Button to an image. 
  1. <Button.Background>  
  2.     <ImageBrush ImageSource="dock.jpg" />  
  3. </Button.Background> 
Listing 15

The new output looks like Figure 8.

Setting Image as Background

Figure 8
 
Adding a Button Click Event Handler
 
The Click attribute of the Button element adds the click event handler. The code in Listing 16 adds the click event handler for a Button. 
  1. <Button x:Name="DrawCircleButton" Height="40" Width="120"   
  2.     Canvas.Left="10" Canvas.Top="10"   
  3.     Content="Draw Circle"  
  4.     VerticalAlignment="Top"   
  5.     HorizontalAlignment="Left">  
  6.     Click="DrawCircleButton_Click"  
  7. </Button> 
Listing 16
 
The code for the click event handler looks like following:
  1. private void DrawCircleButton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.   
Now, whatever code you write in the click event handler that will be executed on the Button click. The code listed in Listing 17 creates a circle on the Button click event handler.
  1. private void DrawCircleButton_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     // creates a Circle  
  4.     Ellipse circle = new Ellipse();  
  5.     circle.Width = 200;  
  6.     circle.Height = 200;  
  7.     circle.Fill = new SolidColorBrush(Colors.Yellow);  
  8.     circle.Stroke = new SolidColorBrush(Colors.Black);  
  9.     circle.StrokeThickness = 4;  
  10.     LayoutRoot.Children.Add(circle);  

Listing 17
 
Mouse Rollover Formatting
 
How about giving some affects to your Button control when a mouse is over the Button and mouse leaves the Button area? We can achieve this by adding MouseEnter and MouseLeave event handler.
 
The code snippet in Listing 18 adds Mouse Enter and Mouse Leave event handlers.
  1. <Button x:Name="DrawCircleButton" Height="40" Width="120"   
  2.     Canvas.Left="10" Canvas.Top="10" Click="DrawCircleButton_Click"  
  3.     MouseEnter="DrawCircleButton_MouseEnter" MouseLeave="DrawCircleButton_MouseLeave"> 
Listing 18

The code listed in Listing 19 sets the background and foreground colors of a Button on mouse enter and mouse leave event handlers. 
  1. private void DrawCircleButton_MouseEnter(object sender, MouseEventArgs e)  
  2. {  
  3.     DrawCircleButton.Background = new SolidColorBrush(Colors.Yellow );  
  4.     DrawCircleButton.Foreground = new SolidColorBrush(Colors.Green);  
  5. }  
  6.   
  7. private void DrawCircleButton_MouseLeave(object sender, MouseEventArgs e)  
  8. {  
  9.     DrawCircleButton.Background = new SolidColorBrush(Colors.Red);  
  10.     DrawCircleButton.Foreground = new SolidColorBrush(Colors.Purple);  

Listing 19
 
Summary
 

In this article, I discussed how we can create a Button control in WPF and C#. We also saw how we can format a Button by setting its border, background, and foreground properties. After that, we saw you to set an image as the background of a Button. In the end of this article, we saw how to create a Button dynamically.


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.