generated from nventive/Template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
RaiseCanExecuteOnDispatcherCommandStrategy.cs
91 lines (77 loc) · 2.41 KB
/
RaiseCanExecuteOnDispatcherCommandStrategy.cs
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Chinook.DynamicMvvm;
namespace Chinook.DynamicMvvm
{
/// <summary>
/// This <see cref="IDynamicCommandStrategy"/> ensures that the <see cref="CanExecuteChanged"/> event is raised using <see cref="IDispatcher.ExecuteOnDispatcher(CancellationToken, Action)"/>.
/// </summary>
public class RaiseCanExecuteOnDispatcherCommandStrategy : DelegatingCommandStrategy
{
private readonly WeakReference<IViewModel> _viewModel;
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
/// <summary>
/// Creates a new instance of <see cref="RaiseCanExecuteOnDispatcherCommandStrategy"/>.
/// </summary>
/// <param name="viewModel">The <see cref="IViewModel"/> from which to access the <see cref="IDispatcher"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="viewModel"/> cannot be null.</exception>
public RaiseCanExecuteOnDispatcherCommandStrategy(IViewModel viewModel)
{
if (viewModel is null)
{
throw new ArgumentNullException(nameof(viewModel));
}
_viewModel = new WeakReference<IViewModel>(viewModel);
}
/// <inheritdoc/>
public override IDynamicCommandStrategy InnerStrategy
{
get => base.InnerStrategy;
set
{
if (base.InnerStrategy != null)
{
base.InnerStrategy.CanExecuteChanged -= OnInnerCanExecuteChanged;
}
base.InnerStrategy = value;
if (base.InnerStrategy != null)
{
base.InnerStrategy.CanExecuteChanged += OnInnerCanExecuteChanged;
}
}
}
/// <inheritdoc/>
public override event EventHandler CanExecuteChanged;
private void OnInnerCanExecuteChanged(object sender, EventArgs e)
{
var hasVM = _viewModel.TryGetTarget(out var viewModel);
if (!hasVM || viewModel.IsDisposed)
{
return;
}
// The event should be raised immediately when the view already has dispatcher access OR when there is no view.
var shouldRaiseImmediately= viewModel.Dispatcher?.GetHasDispatcherAccess() ?? true;
if (shouldRaiseImmediately)
{
RaiseCanExecuteChanged();
}
else
{
_ = viewModel.Dispatcher.ExecuteOnDispatcher(_cts.Token, RaiseCanExecuteChanged);
}
void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
/// <inheritdoc/>
public override void Dispose()
{
base.Dispose();
_cts.Cancel();
_cts.Dispose();
}
}
}