Skip to content

Instantly share code, notes, and snippets.

@resnyanskiy
Created September 25, 2013 07:00
Show Gist options
  • Save resnyanskiy/6696035 to your computer and use it in GitHub Desktop.
Save resnyanskiy/6696035 to your computer and use it in GitHub Desktop.
Base types for MVVM pattern in WPF
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