Created
September 25, 2013 07:00
-
-
Save resnyanskiy/6696035 to your computer and use it in GitHub Desktop.
Base types for MVVM pattern in WPF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.Runtime.CompilerServices; | |
using System.Windows.Input; | |
namespace WpfApp.ViewModels | |
{ | |
class ViewModelBase : INotifyPropertyChanged | |
{ | |
public event PropertyChangedEventHandler PropertyChanged; | |
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) | |
{ | |
if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} | |
// http://msdn.microsoft.com/en-us/magazine/dd419663.aspx | |
public class RelayCommand : ICommand | |
{ | |
readonly Action<object> _execute; | |
readonly Predicate<object> _canExecute; | |
public RelayCommand(Action<object> execute, Predicate<object> canExecute) | |
{ | |
if(execute == null) | |
throw new ArgumentNullException("execute"); | |
_execute = execute; | |
_canExecute = canExecute; | |
} | |
public RelayCommand(Action<object> execute) : this(execute, null) { } | |
public bool CanExecute(object parameter) | |
{ | |
return _canExecute == null || _canExecute(parameter); | |
} | |
public event EventHandler CanExecuteChanged | |
{ | |
add { CommandManager.RequerySuggested += value; } | |
remove { CommandManager.RequerySuggested -= value; } | |
} | |
public void Execute(object parameter) | |
{ | |
_execute(parameter); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment