Benutzer:MovGP0/WPF/Routed Commands

aus Wikipedia, der freien Enzyklopädie
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


Routed Commands

Usage

<Window (...)>
    <StackPanel>
        <TextBox x:Name="textBox1" />
        <TextBox x:Name="textBox2" />
        <Button Command="ApplicationCommands.Cut" Content="Cut" />
        <Button Command="ApplicationCommands.Paste" Content="Paste" />
    </StackPanel>
</Window>

Using custom command implementation

<Window (...)>
    <Window.CommandBindings>
        <CommandBinding Command="ApplicadionCommands.Cut" CanExecute="IsCutExecuteable" Executed="OnCut">
    <Window.CommandBindings>

    <StackPanel>
        <TextBox x:Name="textBox" />
        <Button Command="ApplicationCommands.Cut" Content="Cut" />
        <Button Command="ApplicationCommands.Paste" Content="Paste" />
    </StackPanel>
</Window>

Calling Routed Event imperatively

if(ApplicationCommands.Cut.CanExecute(param))
{
    ApplicationCommands.Cut.Execute(param, textBox);
}

Custom Routed Commands

  • new RoutedCommand instance
  • ExecuteRoutedEventHandler
  • CanExecuteRoutedEventHandler
  • CommandBinding
public static class MyControlCommands
{
    private static RoutedCommand UpdateTextCommand { get; } = new RoutedCommand();
}
<Button Command="local:MyControlCommands.UpdateTextCommand" 
        CommandParameter="Hello World!"
        Content="Click me" />
public MyControl()
{
    CommandBindings.Add(new CommandBinding(MyControlCommands.UpdateTextCommand, OnUpdateText, CanUpdateTextExecute));
}

private void OnUpdateText(object sender, ExecutedRoutedEventArgs args)
{
    // ...
)

private bool CanUpdateTextExecute(object sender, CanExecuteRoutedEventArgs e)
{
    var paramater = e.Parameter;
    if(parameter != null)
        e.CanExecute = true;
}