Binding MediaElement to a ViewModel in a Windows 8 Store App
Posted
by jdanforth
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by jdanforth
Published on Fri, 14 Dec 2012 14:07:15 GMT
Indexed on
2012/12/14
17:04 UTC
Read the original article
Hit count: 255
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.
© ASP.net Weblogs or respective owner