Converting Silverlight Event Handlers in Javascript to .NET Code


Should Silverlight 1.0 RC code just work in Silverlight 1.1 Alpha Refresh? That’s my understanding, but I ran into some issues with Silverlight event handlers in one example, which displays the CurrentState of a MediaElement. 


I kept getting the following error message in Orcas Beta 2.0 when debugging the code with one event handler attached as shown below. 


<MediaElement
    x:Name=”media”
    Source=”xbox.wmv”
    CurrentStateChanged=”media_state_changed”
    Width=”300″ Height=”300″/>


Silverlight error message    
ErrorCode: 2260
ErrorType: ParserError      
Message: AG_E_PARSER_BAD_PROPERTY_VALUE    
XamlFile: Page.xaml    
Line: xxx    
Position: yyy

I knew I could add events by using addEventListener, but I was reluctant because I thought attaching an event handler to a xaml tag was really neat. After struggling for a while on the issue and reading many postings on the web, I realized that maybe 1.1 alpha refresh would rather deal with .net code than javascript at least for handling events. So I decided to convert the javascript functions, which was pretty straightforward.

<!– JavaScript functions that work in Silverlight 1.0 RC –>
 






JavaScript
function media_stop(sender, args)
{
sender.findName(“media”).stop();
}

function media_pause(sender, args)
{
sender.findName(“media”).pause();
}

function media_begin(sender, args)
{
sender.findName(“media”).play();
}

function media_state_changed(sender, args)
{
var mediaStateTextBlock =
sender.findName(“mediaStateTextBlock”);
var media = sender.findName(“media”);
mediaStateTextBlock.Text = media.CurrentState;
}


I then added the following .net code to the Page.xaml file. The application worked, and I was delighted.


……
       
// .NET event handlers converted from JavaScript functions; the code works in Silverlight 1.1 Alpha Refresh
  public void Page_Loaded(object o, EventArgs e)
        {
            // Required to initialize variables
            InitializeComponent();
        }


        void media_begin(object sender, MouseEventArgs e)  {media.Play(); }


        void media_pause(object sender, MouseEventArgs e) {media.Pause();}
              
        void media_stop(object sender, MouseEventArgs e) {media.Stop();}


        void media_state_changed(object sender, EventArgs e) {mediaStateTextBlock.Text  = media.CurrentState;}
……