Absolute minimal MVVM
Since I have plans for showing some examples using WPF with MVVM, I thought it would be a good idea to post the code for a very basic MVVM template.
This is so I don't have to rely on some advanced frameworks. And this way the examples can focus on the issue at hand.
The files may be placed in a library and referenced by several projects, or they may be copied inside the project itself.
The first class to be used is the base for handling INotifyPropertyChanged in the ViewModels and models:
using System.ComponentModel; using System.Runtime.CompilerServices; namespace AbsoluteMiniMvvm { public class PropertyChangedBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
The second is for the Command:
namespace AbsoluteMiniMvvm { public class Command : ICommand { public delegate void ICommandOnExecute(); public delegate bool ICommandOnCanExecute(); private ICommandOnExecute _execute; private ICommandOnCanExecute _canExecute; public Command(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod = null) { _execute = onExecuteMethod; _canExecute = onCanExecuteMethod; } #region ICommand Members public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { return _canExecute?.Invoke() ?? true; } public void Execute(object parameter) { _execute?.Invoke(); } #endregion } }
Usage
The classes in the ViewModels or Model should then inherit the "PropertyChangedBase" . And the RaisePropertyChanged should be called in the properties:
using AbsoluteMiniMvvm;
public class MainWindowViewModel : PropertyChangedBase { // .... private string _name; public string Name { get { return _name; } set { if (_name == value) return; _name = value; RaisePropertyChanged(); } } // ... }
And for an example of using commands:
using AbsoluteMiniMvvm;
public class MainWindowViewModel : PropertyChangedBase { public Command DoSomethingCommand { get { return new Command(() => { // Code to run for this command }, () => { // Code to check f we can run (true/false) return true; }); } } }
And the command is bound in the UI like this:
<Window.DataContext> <vm:MainWindowViewModel/> </Window.DataContext> <Button Content="{Binding Name}" Command="{Binding DoSomethingCommand}"/>
* Disclaimer!
The code is of course collected from various sources on the net. Most likely StackOverflow, some blogs or forums. Too many to keep track of, so I apoligize that I don't have links or names...
The minds that came up with the original ideas and soloutions deserve all the credit. Thanks to the community for sharing. :-)
Comments
Post a Comment