Monday, January 26, 2009

How to Change the Startup Class

Another great tip from Mike Snow. Read the original article here 

When a Silverlight application is launched the entry point is a class that inherits from System.Windows.Application. By default, when you create a new Silverlight application project, this would be your App class which gets defined in App.xaml.cs. You can, however, change which startup class you want to use. In fact, if you do not plan to use XAML at all you can reduce the size of your application by deleting the Page and App classes including the XAML and code behind files. 

To accomplish this follow these steps: 

Step 1. Create a new Silverlight application project adding a new ASP.net web project to host the Silverlight app. 

Step 2. Delete App.xaml and Page.xaml (the CS files will be deleted also). 

Step 3. Create a new class and call it StartupTest.cs 

Step 4. Modify your new class to inherit from Application as seen here:


public class StartupTest : Application

{

    public StartupTest()

    {

    }

}



Step 5. Right click on your Silverlight application project in the Solution Explorer of VS. From the context menu choose Properties. This will bring up the Properties dialog. Click on the Silverlight tab at the top-left and change the Startup object to be your class as seen circled here: image

Step 6. Go back to your StartupTest class. Add an event to monitor for when the application has started. You don’t want to do anything until after this event has started.


public class StartupTest : Application

{

    public StartupTest()

    {

        this.Startup += new StartupEventHandler(StartupTest_Startup);

    }

 

 

    void StartupTest_Startup(object sender, StartupEventArgs e)

    {

    }

}



Step 7. The Application.RootVisual is root pointer to the main application UI. You will need to create this object to point an object such as a Grid or Canvas control. Once created, you can add additional controls to the children as you see fit. In the example below, I have created a Canvas as the root and configured its background color to be black, its width to be 800 and height to be 600. Also, I have added a Textbox to the Canvas control.


void StartupTest_Startup(object sender, StartupEventArgs e)

{

    this.RootVisual = new Canvas();

 

    ((Canvas)this.RootVisual).Width = 800;

    ((Canvas)this.RootVisual).Height = 600;

    ((Canvas)this.RootVisual).Background = new SolidColorBrush(Colors.Black);

 

    TextBlock tb = new TextBlock();

    tb.Foreground = new SolidColorBrush(Colors.White);

    tb.FontSize = 20;

    tb.Text = "NO XAML NEEDED!!!";

 

    ((Canvas)this.RootVisual).Children.Add(tb);

}



Step 8. Run the application and you will see the following image rendered in your browser: image Technorati Tags:

No comments: