Dynamically Add Control in LightSwitch 2012

Here we will see how to dynamically add controls in a LightSwitch Application (Visual C#) in Visual Studio 2012.

The following is the procedure for dynamically adding a control.

Step 1

Open the Solution Explorer.

sol explorer.jpg

Step 2


In the Solution Explorer, right-click on the Screens and choose "Add Screen".

src add.jpg

Step 3

The Add New Screen dialog box appears. Select the "New Data Screen" from the Screen Template, under screen information, choose "None" under screen data and provide a name to the screen and click the "OK" button.

New.jpg

The Screen Designer appears.

src desi.jpg

Step 4

Click on the "Add" button and choose "New Custom Control".

new custom ctrl.jpg

Step 5

The Add Custom Control dialog box will appear. From that dialog box select the StackPanel Control and click the "OK" button.

Add custom ctrl.jpg

The custom control is added to the Screen Designer.

src desi1.jpg

Step 6

Go to the Menu Bar, click on the Write Code option, a drop down list will appear, select the "the _created()" method from the list.

created method.jpg

The code designer appears.

using System;

using System.Linq;

using System.IO;

using System.IO.IsolatedStorage;

using System.Collections.Generic;

using Microsoft.LightSwitch;

using Microsoft.LightSwitch.Framework.Client;

using Microsoft.LightSwitch.Presentation;

using Microsoft.LightSwitch.Presentation.Extensions;

using System.Windows.Controls;

namespace LightSwitchApplication

{

    public partial class CreateNew

    {

        partial void CreateNew_Created()

        {

            // Write your code here.

            this.FindControl("ScreenContent").ControlAvailable += new EventHandler<ControlAvailableEventArgs>(New_CtrlAvailable);

        }

 

        void New_CtrlAvailable(object sender, ControlAvailableEventArgs e)

        {

            if (e.Control is StackPanel)

            {

                StackPanel panel = (StackPanel)e.Control; // checking if control type is StackPanel

 

                HyperlinkButton link = new HyperlinkButton();

                link.Content = "yahoo";

                link.NavigateUri = new Uri("http://yahoo.com");

                link.TargetName = "_blank";

                panel.Children.Add(link);

 

            }

        }

    }

}

Step 9


Press F5 to run the application.

Yahoo.jpg

Click on the link content in the output, the link will be opened.

output1.jpg