laatzen/Common/OmniPlus/InspectionUI/ViewModels/VM.cs
2024-02-20 12:17:07 +01:00

145 lines
4.1 KiB
C#

namespace InspectionUI.ViewModels
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
public abstract class VM : INotifyPropertyChanged, IDisposable
{
private static readonly Dispatcher dispatcher = Application.Current.Dispatcher;
protected VM()
{
App.Exiting += this.Dispose;
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual void Dispose()
{
App.Exiting -= this.Dispose;
}
protected void WaitAll(List<Task> tasks, Action continuationCallback = null)
{
if (tasks is null || tasks.Count == 0)
{
return;
}
Task.Factory
.ContinueWhenAll(tasks.ToArray(), _tasks =>
{
tasks.Clear();
continuationCallback?.Invoke();
})
.Wait();
}
protected void NotifyPropertyChanged()
{
if (this.PropertyChanged != null)
{
dispatcher.Invoke(new Action(() =>
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(default(string)));
}));
}
}
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (this.PropertyChanged != null)
{
dispatcher.Invoke(new Action(() =>
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}));
}
}
protected void DispatcherInvoke(Action action)
{
dispatcher.Invoke(action);
}
protected void Set(Action setExpression, [CallerMemberName] string property = "")
{
this.DispatcherInvoke(setExpression);
this.NotifyPropertyChanged(property);
}
protected Task StartNewTask(Action action, CancellationToken cancellationToken = default(CancellationToken))
{
return Task
.Factory
.StartNew(action, cancellationToken);
}
protected Task StartNewTask(Action<object> action, object state, CancellationToken cancellationToken = default(CancellationToken))
{
return Task
.Factory
.StartNew(action, state, cancellationToken);
}
protected class Command : ICommand
{
private readonly Action executable;
public Command(Action executable)
{
this.executable = executable;
}
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public bool CanExecute(object _)
{
return this.executable != null;
}
public void Execute(object _)
{
this.executable?.Invoke();
}
}
protected class Command<T> : ICommand
{
private readonly Action<T> executable;
public Command(Action<T> executable)
{
this.executable = executable;
}
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public bool CanExecute(object _)
{
return this.executable != null;
}
public void Execute(object parameter)
{
this.executable?.Invoke(parameter is T t ? t : default(T));
}
}
}
}