Last active
October 1, 2021 10:26
-
-
Save SchreinerK/0aa450669ba0f66dbf821f92b15c1a66 to your computer and use it in GitHub Desktop.
KsWare.Presentaion.Input.CommandBindingMapper
This file contains 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
// GIST: https://gist.github.com/SchreinerK/0aa450669ba0f66dbf821f92b15c1a66 | |
using System.Windows; | |
using System.Windows.Data; | |
using System.Windows.Input; | |
using KsWare.Presentation.ViewFramework; | |
// ReSharper disable once CheckNamespace | |
namespace KsWare.Presentation.Input { | |
/// <summary> | |
/// Provides a <see cref="CommandBinding"/> for redirecting a <see cref="RoutedUICommand"/> to a command in a view model. | |
/// </summary> | |
/// <example> | |
/// <code language="XAML"> | |
/// <UserControl DataContext="UserControlViewModel"> | |
/// <TextBox> | |
/// <UIElement.CommandBindings> | |
/// <CommandBindingMapper Command="ApplicationCommands.Help" CommandBinding="{RootBinding Path=ContextHelpCommand}"/> | |
/// </UIElement.CommandBindings> | |
/// </TextBox> | |
/// ... | |
/// </code> | |
/// <code language="C#"> | |
/// class UserControlViewModel { | |
/// public ICommand ContextHelpCommand {get} | |
/// } | |
/// </code> | |
/// </example> | |
/// <seealso cref="UIElement.CommandBindings"/> | |
public class CommandBindingMapper : CommandBinding { | |
private Binding _commandBinding; | |
private readonly BindingProxy _proxy = new BindingProxy(); | |
/// <inheritdoc /> | |
public CommandBindingMapper() { | |
CanExecute += OnCanExecute; | |
Executed += OnExecuted; | |
} | |
private void OnExecuted(object sender, ExecutedRoutedEventArgs e) { | |
if (_proxy.Value is ICommand command) { | |
command.Execute(e.Parameter); | |
} | |
} | |
private void OnCanExecute(object sender, CanExecuteRoutedEventArgs e) { | |
if (_proxy.Value is ICommand command) { | |
command.CanExecute(e.Parameter); | |
} | |
} | |
/// <summary> | |
/// Binding to a <see cref="ICommand"/> in a view model. | |
/// </summary> | |
/// <example> | |
/// <code> | |
/// <CommandBindingMapper Command="ApplicationCommands.Help" CommandBinding="{RootBinding Path=ContextHelpCommand}"/> | |
/// </code> | |
/// </example> | |
/// <seealso cref="RootBindingExtension"/> | |
public Binding CommandBinding { | |
get => _commandBinding; | |
set { | |
_commandBinding = value; | |
BindingOperations.SetBinding(_proxy, BindingProxy.ValueProperty, value); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment