views:

315

answers:

1

I'm trying to write a silverlight application that takes in InitParams and then uses those InitParams to make a change to the Source of the MediaElement on the page. I'm trying to figure out the proper place to put my code.

I watched Tim Heuer's excellent video on InitParams, but in the video (which was for Silverlight 2), it shows the following on the Page.xaml.cs:

void Page_Loaded(object sender, RoutedEventArgs e)
    {

    }

I don't see Page_Loaded when I open MainPage.xaml.cs, and I'm wondering if that was automatically created in the Silverlight 2 SDK and left out of the Silverlight 3 SDK. Or perhaps Tim added that in his video manually.

I find that I can go into the opening UserControl tag of MainPage.xaml and add Loaded="<New_Event_Handler>" which creates the following in MainPage.xaml.cs:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {

    }

By default, there's also the following in MainPage.xaml.cs, which is run during the Application_Startup event in App.xaml.cs:

public MainPage()
    {            
        InitializeComponent();
    }

I need to figure out where is the best place to insert my code to change the Source on my MediaElement in my xaml. Should I put it in MainPage? Should I add the Loaded event handler and put it into UserControl_Loaded? If it's supposed to be Page_Loaded, where do I find that in Silverlight 3?

Any help would be much appreciated.

+2  A: 

"UserControl_Loaded" and "Page_Loaded" are just method names and the names don't matter (you could name the method "Foo" if you wanted). What makes these methods do anything is the fact that they are attached to the Loaded event on the UserControl (which is what you did when you edited the MainPage.xaml file).

KeithMahoney
Ok, so that makes sense. Still, though, is there an advantage to placing them in UserControl_Loaded instead of MainPage()?
Ben McCormack
The difference between placing code in the constructor vs the Loaded event handler is when these methods get called. The constructor will be called first as soon as an instance of the control is instantiated. The Loaded event will fire sometime after that. One advantage that Loaded sometimes has is that any properties that are set on the object in Xaml will have their values initialized by the time Loaded is fired - not so with the constructor. But since you are calling InitializeComponent() in your constructor, this doesn't matter as long as your code goes after that call.
KeithMahoney
thanks for the info!
Ben McCormack