Silverlight Button Control using C#

Updated on 24 Feb 2012,
Published on 26 Jul 2011

The Silverlight Button control can be added to the application using three different ways in a similar way like we do in ASP.Net web applications. After adding a Button control onto the Silverlight User control you must know the various types of properties of that can be customized to make it more attractive. You must also know the basics of controls to attach the event handler to the controls for creating the interactive applications. Following are the different ways for adding the Button control to the Silverlight user control:

1. Adding the control by double clicking it on the toolbox at the left side of Visual Web Developer 2010 Express Edition while working on a Silverlight application.

2. Adding the control programmatically using C#/VB.Net code.

3. Adding the control by writing code in the XAML file of Silverlight User control directly.

Adding Button Control from Silverlight Toolbox

It's a common way to add a Button control on the Silverlight User control while working in design view. Locate the Button control on the toolbox ribbon on the left side of the Visual web developer. Double-clicking on the control adds it on the design view. When you add the button control by double-clicking or dragging it on the design view it auto generates the following code in the XAML code file:

<Button Content="Button" 
        Height="23" 
        HorizontalAlignment="Left" 
        Margin="10,10,0,0" 
        Name="button1" 
        VerticalAlignment="Top" 
        Width="75" />

You can also write this code directly into the XAML code file by switching the Silverlight user control's view to XAML source view.

Adding Button Control using C# code

The following C# code shows the way to add the Button control on the Layout Panel of User control of Silverlight application programmatically:

public MainPage()
{
    // create a button instance
    Button button1 = new Button();

    InitializeComponent();

    // set its properties
    button1.Height = 23;
    button1.Width = 75;
    button1.Margin = new Thickness(10, 10, 0, 0);
    button1.Content = "Button";
    button1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
    button1.VerticalAlignment = System.Windows.VerticalAlignment.Top;

    // add the button to the Layout Panel as a child control
    this.LayoutRoot.Children.Add(button1);
}

Continue to next tutorial: Silverlight Button Control Click Event using C# to learn how to handle the click event of a button.

0 Responses to "Silverlight Button Control using C#"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers