Skip to content

Instantly share code, notes, and snippets.

@KaiserWerk
Last active December 30, 2020 20:54
Show Gist options
  • Save KaiserWerk/f92cd361a0bedb465d0ec1e80c9dbb92 to your computer and use it in GitHub Desktop.
Save KaiserWerk/f92cd361a0bedb465d0ec1e80c9dbb92 to your computer and use it in GitHub Desktop.
C# MVVM Simple Implementation
using System;
using System.Collections.Generic;
namespace Mvvm
{
public class Ioc
{
private static Dictionary<Type, object> classes = new Dictionary<Type, object>();
public static void Register<T>(params object[] parameters) where T : class
{
bool added = classes.TryAdd(typeof(T), Activator.CreateInstance(typeof(T), parameters));
if (!added)
throw new Exception($"Could not register type '{typeof(T)}'; is it already registered?");
}
public static T GetInstance<T>()
{
bool exists = classes.TryGetValue(typeof(T), out object cls);
if (!exists)
throw new Exception($"No instance of type '{typeof(T)}' registered!");
return (T)cls;
}
}
}
using System;
using System.Collections.Generic;
namespace Mvvm
{
public class Messenger
{
private static Dictionary<Type, Action<object>> registrants = new Dictionary<Type, Action<object>>();
private static readonly object registerLock = new object();
private static readonly object sendLock = new object();
public static void Send<T>(T obj) where T : class
{
lock (sendLock)
{
foreach (var item in registrants)
{
if (item.Key == typeof(T))
{
item.Value(obj);
//break; // remove this to allow multiple recipients
}
}
// alternative to using a loop
//var set = registrants.First(e => e.Key == typeof(T));
//set.Value?.Invoke(obj);
}
}
public static void Register<T>(Action<object> act) where T : class
{
lock (registerLock)
{
registrants.Add(typeof(T), act);
}
}
}
}
using System;
using System.Windows.Input;
namespace Mvvm
{
public class RelayCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private Action<object> execute;
private Func<object, bool> canExecute;
public RelayCommand(Action<object> ex, Func<object, bool> canEx)
{
this.execute = ex;
this.canExecute = canEx;
}
public RelayCommand(Action<object> ex)
{
this.execute = ex;
}
public bool CanExecute(object parameter)
{
if (this.canExecute == null)
return true;
if (this.canExecute(parameter) == true)
return true;
return false;
}
public void Execute(object parameter)
{
this.execute?.Invoke(parameter);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment