Last active
March 5, 2019 22:26
-
-
Save formix/2f5517b47c89d262f5b5b66005d9cd7a to your computer and use it in GitHub Desktop.
Base class vor a MVVM ViewModel
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.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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works with the propvm snippet.