Created
August 20, 2024 15:37
-
-
Save doxxx/911ba2af9847362e12e01a045273184e to your computer and use it in GitHub Desktop.
Helper to integrate CommunityToolkit.Mvvm.Input.IRelayCommand with WPF CommandManager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Windows.Input; | |
using CommunityToolkit.Mvvm.Input; | |
public static class RelayCommandHelpers | |
{ | |
private static readonly List<WeakReference<IRelayCommand>> _commands = new(); | |
public static void RegisterCommandsWithCommandManager(object container) | |
{ | |
if (_commands.Count == 0) | |
CommandManager.RequerySuggested += OnRequerySuggested; | |
foreach (var p in container.GetType().GetProperties()) | |
{ | |
if (p.PropertyType.IsAssignableTo(typeof(IRelayCommand))) | |
{ | |
var command = (IRelayCommand?)p.GetValue(container); | |
if (command != null) | |
_commands.Add(new WeakReference<IRelayCommand>(command)); | |
} | |
} | |
} | |
private static void OnRequerySuggested(object? sender, EventArgs args) | |
{ | |
foreach (var command in _commands) | |
{ | |
if (command.TryGetTarget(out var c)) | |
c.NotifyCanExecuteChanged(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use, call this method from the constructor of a WPF view model that has
IRelayCommand
properties: