Tuesday, 10 June 2008
| Main | How To Switch Between Remote Desktop Ses... »
I've been working on a video player app over the last few weeks using Silverlight 2.0 Beta 1, so when beta 2 was released last week I was intrigued to see whether my app would still work; and the short answer is that it did not :-(

The easy bits to fix were the compile time errors, and i'd been expecting a few of them having read the beta 2 breaking changes doc in advance whilst waiting for beta 2 to download. The problem that stumped me was the video playback at runtime: I was hearing the audio but no video was displaying.

The method i'm using for video playback is to use a hidden MediaElement to play the video, and then use a VideoBrush to 'paint' the video onto a Rectangle; You 'attach' the VideoBrush to a MediaElement by setting the VideoBrush.SourceName=MediaElement.Name.

Both my MediaElement and VideoBrush are created dynamically in the codebehind, and because because we need the MediaElement to have a Name we have to use XamlReader.Load() to create the MediaElement, because the Name property is read only and can not be set from within your code: 

MediaElement me1= XamlReader.Load(@"<MediaElement 
                                xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                                Name='me1' Opacity='0' />") as MediaElement;
LayoutRoot.Children.Add(mediaElement);
VideoBrush vb = new VideoBrush();
vb.SourceName = me1.Name;
MyRectangle.Fill=vb;

That code works fine in beta 1, but in beta 2 MyRectangle remains blank!

The clue to fixing this is included in the breaking changes doc:

"XamlReader.Load(string) has been changed to always create an implicit namescope."

So what appears to be happening under beta 2 is that the VideoBrush is searching for a MediaElement named 'me1' in the default Xaml namescope, but it can not find it as me1 was created in its own implicit namescope.


So how do we fix this? The method I have used is to create the VisualBrush within the same namescope as the MediaElement, and i've done this by including the VisualBrush in the MediaElement's Resources:

MediaElement me1 = XamlReader.Load(@"<MediaElement
                                 xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                                 Name='me1' AutoPlay='False' Opacity='0.0' IsHitTestVisible='False' >
                                    <MediaElement.Resources>
                                       <VideoBrush Name='vb1' SourceName='me1'/>
                                    </MediaElement.Resources>
                                    </MediaElement>") as MediaElement;
VideoBrush vb = me1.FindName("vb1") as VideoBrush;
MyRectangle.Fill=vb;

After doing this, MyRectangle once again displays the video :-)



Tuesday, 10 June 2008 12:37:12 (GMT Standard Time, UTC+00:00)  #      Comments [0]  |  Trackback Related posts:

Comments are closed.