Skip to content

Instantly share code, notes, and snippets.

@doxxx
Created August 20, 2024 15:37
Show Gist options
  • Save doxxx/911ba2af9847362e12e01a045273184e to your computer and use it in GitHub Desktop.
Save doxxx/911ba2af9847362e12e01a045273184e to your computer and use it in GitHub Desktop.
Helper to integrate CommunityToolkit.Mvvm.Input.IRelayCommand with WPF CommandManager
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();
}
}
}
@doxxx
Copy link
Author

doxxx commented Aug 20, 2024

To use, call this method from the constructor of a WPF view model that has IRelayCommand properties:

public class MyViewModel : ObservableObject
{
    public IRelayCommand SomeCommand { get; }

    public MyViewModel()
    {
        SomeCommand = new AsyncRelayCommand(() => DoStuffAsync(), () => true);

        RelayCommandHelpers.RegisterCommandsWithCommandManager(this);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment