public class MediaClass : ViewModelBase { private MediaElement mediaplay; public MediaElement MediaPaly { get { return mediaplay; } set { Set("MediaPlay", ref mediaplay, value); } } }
public class MainViewModel : ViewModelBase { private MediaClass mediaTest; public MediaClass MediaTest { get { return mediaTest; } set {Set("MediaTest",ref mediaTest,value); } } public MainViewModel() { mediaTest = new MediaClass(); MediaPlayCommand = new RelayCommand(Play); } public RelayCommand MediaPlayCommand { get; private set; } public async void Play() { FileOpenPicker filePicker = new FileOpenPicker(); filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary; filePicker.FileTypeFilter.Add(".wmv"); filePicker.FileTypeFilter.Add(".mp4"); filePicker.ViewMode = PickerViewMode.Thumbnail; StorageFile localVideo = await filePicker.PickSingleFileAsync(); if (localVideo != null) { // Open the selected file and set it as the MediaElement's source IRandomAccessStream stream = await localVideo.OpenAsync(FileAccessMode.Read); this.MediaTest.MediaPaly = MediaTest.MediaPaly; MediaTest.MediaPaly.SetSource(stream, localVideo.ContentType); } } }
x:Class="MediaTest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:MediaTest" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" DataContext="{Binding Main, Mode=OneWay, Source={StaticResource Locator}}"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <MediaElement x:Name="VideoSource" HorizontalAlignment="Left" Height="564" VerticalAlignment="Top" Width="1201" AreTransportControlsEnabled="True" Margin="96,37,0,0" Source="{Binding MediaTest.MediaPaly.Source}" /> <Button Height="45" Margin="861,651,0,72" Width="99" Content="Open File" Command="{Binding MediaPlayCommand, Mode=OneWay}"/> </Grid>
MediaTest.MediaPaly.SetSource(stream, localVideo.ContentType); // System.NullReferenceException
media Element Binding