I am still studying the ropes of MVVM and WPF, and at the moment I am trying to create a media player using MVVM. After an intensive Google search, I decided that using CommanParameter would be the best way to avoid the code. I believe that the code and XAML look great, but there is no magic - AKA does not happen.
Is there some kind of soul that could take a look at my code and give me some tips? As always, I really appreciate your answers. Please ignore my plurals in RelayCommands, it was too late :)
Xaml
<MediaElement Name="MediaElement" Source="{Binding VideoToPlay}" Width="400" Height="180" Stretch="Fill" LoadedBehavior="Manual" UnloadedBehavior="Manual"/> <Slider Name="timelineSlider" Margin="5" Width="250" HorizontalAlignment="Center"/> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <Button Command="{Binding PlayMediaCommand}" CommandParameter="{Binding ElementName=MediaElement, Mode=OneWay}"><<</Button>
FROM#
class MediaPlayerViewModel: INotifyPropertyChanged { private MediaElement MyMediaElement; private Uri _videoToPlay; public Uri VideoToPlay { get { return _videoToPlay; } set { _videoToPlay = value; OnPropertyChanged("VideoToPlay"); } } void SetMedia() { OpenFileDialog dlg = new OpenFileDialog(); dlg.InitialDirectory = "c:\\"; dlg.Filter = "Media files (*.wmv)|*.wmv|All Files (*.*)|*.*"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() == true) { VideoToPlay = new Uri(dlg.FileName); } } RelayCommands _openFileDialogCommand; public ICommand OpenFileDialogCommand { get { if (_openFileDialogCommand == null) { _openFileDialogCommand = new RelayCommands(p => SetMedia(), p => true); } return _openFileDialogCommand; } } RelayCommands _playMediaCommand; public ICommand PlayMediaCommand { get { if (_playMediaCommand == null) { _playMediaCommand = new RelayCommands(p => PlayMedia(p), p => true); } return _playMediaCommand; } } void PlayMedia(object param) { var paramMediaElement = (MediaElement)param; MyMediaElement = paramMediaElement; MyMediaElement.Source = VideoToPlay; MyMediaElement.Play(); } protected void OnPropertyChanged(string propertyname) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyname)); } public event PropertyChangedEventHandler PropertyChanged; class RelayCommands: ICommand { private readonly Predicate<object> _canExecute; private readonly Action<object> _execute; public event EventHandler CanExecuteChanged; public RelayCommands(Action<object> execute) : this(execute, null) {} public RelayCommands(Action<object> execute, Predicate<object> canExecute) { _execute = execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } public void Execute(object parameter) { _execute(parameter); } public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } }
c # wpf mvvm
Iris classon
source share