Binding MediaElement to a ViewModel in a Windows 8 Store App

If you want to play a video from your video-library in a MediaElement control of a Metro Windows Store App and tried to bind the Url of the video file as a source to the MediaElement control like this, you may have noticed it’s not working as well for you:

<MediaElement Source="{Binding Url}" />

I have no idea why it’s not working, but I managed to get it going using  ContentControl instead:

<ContentControl Content="{Binding Video}" />

The code behind for this is:

protected override void OnNavigatedTo(NavigationEventArgs e)

{

    _viewModel = new VideoViewModel("video.mp4");

    DataContext = _viewModel;

}

And the VideoViewModel looks like this:

public class VideoViewModel

{

    private readonly MediaElement _video;

    private readonly string _filename;

 

    public VideoViewModel(string filename)

    {

        _filename = filename;

        _video = new MediaElement { AutoPlay = true };

        //don't load the stream until the control is ready

        _video.Loaded += VideoLoaded;

    }

 

    public MediaElement Video

    {

        get { return _video; }

    }

 

    private async void VideoLoaded(object sender, RoutedEventArgs e)

    {

        var file = await KnownFolders.VideosLibrary.GetFileAsync(_filename);

        var stream = await file.OpenAsync(FileAccessMode.Read);

        _video.SetSource(stream, file.FileType);

    }

}

I had to wait for the MediaElement.Loaded event until I could load and set the video stream.

Published Friday, December 14, 2012 3:07 PM by jdanforth
Filed under: ,

Comments

No Comments