1
0
mirror of synced 2024-11-15 01:33:51 +00:00
PettingZoo/PettingZoo.WPF/ViewModel/BaseViewModel.cs

65 lines
2.0 KiB
C#
Raw Normal View History

2021-12-18 17:40:22 +00:00
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace PettingZoo.WPF.ViewModel
{
public class BaseViewModel : INotifyPropertyChanged
{
2021-12-18 17:40:22 +00:00
private int commandsChangedDisabled;
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, IEqualityComparer<T>? comparer = null, [CallerMemberName] string? propertyName = null,
DelegateCommand[]? delegateCommandsChanged = null,
string[]? otherPropertiesChanged = null)
{
if ((comparer ?? EqualityComparer<T>.Default).Equals(field, value))
return false;
field = value;
RaisePropertyChanged(propertyName);
if (otherPropertiesChanged != null)
{
foreach (var otherProperty in otherPropertiesChanged)
RaisePropertyChanged(otherProperty);
}
2021-12-18 17:40:22 +00:00
// ReSharper disable once InvertIf
if (delegateCommandsChanged != null)
{
foreach (var delegateCommand in delegateCommandsChanged)
delegateCommand.RaiseCanExecuteChanged();
}
return true;
}
2021-12-18 17:40:22 +00:00
protected void DisableCommandsChanged(Action updateFields, params DelegateCommand[] delegateCommandsChangedAfter)
{
commandsChangedDisabled++;
try
{
updateFields();
}
finally
{
commandsChangedDisabled--;
if (commandsChangedDisabled == 0)
{
foreach (var delegateCommand in delegateCommandsChangedAfter)
delegateCommand.RaiseCanExecuteChanged();
}
}
}
}
}