-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathViewModelBase.txt
More file actions
69 lines (58 loc) · 2.34 KB
/
ViewModelBase.txt
File metadata and controls
69 lines (58 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
namespace YourNamespace
{
public class ViewModelBase : INotifyPropertyChanged
{
// The PropertyChanged event is defined by the INotifyPropertyChanged interface.
public event PropertyChangedEventHandler PropertyChanged;
// This method is used to notify when a property value changes.
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// This method sets the value of a property and raises the PropertyChanged event if the value changes.
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
// RelayCommand class to handle command binding in ViewModel.
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool> _canExecute;
// Event that gets fired when CanExecute changes.
public event EventHandler CanExecuteChanged;
// Constructor for commands without a condition.
public RelayCommand(Action<object> execute) : this(execute, null) { }
// Constructor for commands with a condition.
public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
// Determines if the command can be executed.
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
// Executes the command action.
public void Execute(object parameter)
{
_execute(parameter);
}
// Raises the CanExecuteChanged event to notify the UI of state changes.
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}