Skip to content

Instantly share code, notes, and snippets.

@formix
Last active March 5, 2019 22:26
Show Gist options
  • Save formix/2f5517b47c89d262f5b5b66005d9cd7a to your computer and use it in GitHub Desktop.
Save formix/2f5517b47c89d262f5b5b66005d9cd7a to your computer and use it in GitHub Desktop.
Base class vor a MVVM ViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Template.Project.ViewModels
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly Dictionary<string, object> _properties;
public ViewModelBase()
{
// Makes sure that the internal hash table won't get resized
// while being filled.
var projectedSize = GetType().GetProperties().Length / 0.7;
var size = (int)Math.Ceiling(projectedSize);
_properties = new Dictionary<string, object>(size);
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(propertyName));
}
protected virtual T Get<T>(string propertyName)
{
if (!_properties.ContainsKey(propertyName))
{
return default(T);
}
return (T)_properties[propertyName];
}
protected virtual void Set(string propertyName, object value)
{
_properties[propertyName] = value;
OnPropertyChanged(propertyName);
}
}
}
@formix
Copy link
Author

formix commented Nov 26, 2018

Works with the propvm snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment