Developing a family library plugin involves many interactive commands and requires many bindings. Using MVVM to directly bind Commands makes the entire ViewModel too messy. Here, an ICommandManage interface is created to manage Commands. The ValueConvert interface in WPF is used to convert the passed string into an ICommand command.

C#

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
public interface ICommandManager
{
void RegisterCommand(string name, ICommand? command);
void UnRegisterCommand(string name);
ICommand GetCommand(string name);
}

public class CommandManager:ICommandManager
{
private readonly Dictionary<string, ICommand?> _commands = new Dictionary<string, ICommand?>();
public void RegisterCommand(string name, ICommand? command)
{
_commands[name] = command;
}

public void UnRegisterCommand(string name)
{
_commands.Remove(name);
}

public ICommand GetCommand(string name)
{
return _commands.TryGetValue(name, out ICommand? command) ? command : null;
}
}

ViewModel:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
        private  ICommandManager _commandManager = new CommandManager();

public ICommandManager CommandManager
{
get => _commandManager;
set
{
_commandManager = value;
OnPropertyChanged(nameof(CommandManager));
}
}



_commandManager.RegisterCommand("ButtonCommand" , new MyCommand(param => { MessageBox.Show("Hello");} , para=>true));
_commandManager.RegisterCommand("SelectedItemCommand" ,new MyCommand(GetSelectedItem ,para => true ));
_commandManager.RegisterCommand("SkipToTargetPageCommand" , new MyCommand(SkipToTargetPage , para=>true));
_commandManager.RegisterCommand("SkipToPreviousPageCommand", new MyCommand(SkipToPreviousPage , para=>true));
_commandManager.RegisterCommand("SkipToNextPageCommand", new MyCommand(SkipToNextPage, para=>true));
_commandManager.RegisterCommand("PromptFamilyCommand", new MyCommand(PromptFamily, para=>true));

Converter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CommandConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is ICommandManager commandManager && parameter is string commandName)
{
return commandManager.GetCommand(commandName);
}
return null;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

WPF

1
2
3
4
5
6
7
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction
Command="{Binding Path=CommandManager , ConverterParameter=ButtonCommand , Converter={StaticResource CommandConverter} }">
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>