Skip to content

Instantly share code, notes, and snippets.

@tshm
Created March 21, 2016 18:30
Show Gist options
  • Save tshm/b7d12aa3dfad9fcaa00e to your computer and use it in GitHub Desktop.
Save tshm/b7d12aa3dfad9fcaa00e to your computer and use it in GitHub Desktop.
ViewModel base class for WPF application.
using System;
using System.Windows.Threading;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Windows;
namespace ViewModels
{
/// <summary>
/// The base class of ViewModel which implements
/// INotifyPropertyChanged interface.
/// Also implements dispatcher method for multithreaded property access.
/// </summary>
internal class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
/// <summary>
/// Helper function to dispatch property access so that it can be done
/// from background thread.
/// </summary>
/// <param name="f">side effect action to be performed.</param>
protected void Dispatch(Action f) => Application.Current.Dispatcher.Invoke(f);
/// <summary>
/// Helper function to dispatch property access so that it can be done
/// from background thread.
/// </summary>
/// <param name="f">side effect action to be performed.</param>
protected TResult Dispatch<TResult>(Func<TResult> f) => Application.Current.Dispatcher.Invoke(f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment