namespace WpfAppDataGridHelp.ViewModels
{
internal class JobViewModel : ViewModelBase
{
private string _name = "";
public string Name
{
get => _name;
set => Set(ref _name, value);
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace WpfAppDataGridHelp.ViewModels;
public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
{
protected ViewModelBase()
{
}
public virtual string? DisplayName { get; protected set; }
protected virtual bool ThrowOnInvalidPropertyNames { get; private set; }
[field: NonSerialized]
public event PropertyChangedEventHandler? PropertyChanged;
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
if (ThrowOnInvalidPropertyNames) throw new Exception(msg);
Debug.Fail(msg);
}
}
protected void RaisePropertyChanged(string propertyName)
{
VerifyPropertyName(propertyName);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public virtual void RaisePropertyChanged<T>(
[CallerMemberName] string? propertyName = null,
T? oldValue = null,
T? newValue = null)
where T : class
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentException("This method cannot be called with an empty string", nameof(propertyName));
RaisePropertyChanged(propertyName);
}
protected bool Set<T>(
ref T? field,
T? newValue,
[CallerMemberName] string? propertyName = null)
where T : class
{
if (EqualityComparer<T>.Default.Equals(field, newValue))
return false;
var oldValue = field;
field = newValue;
RaisePropertyChanged(propertyName, oldValue, field);
return true;
}
protected virtual void OnDispose()
{
}
public void Dispose()
{
OnDispose();
}
}