Benutzer:MovGP0/WPF/Routed Commands

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


Routed Commands

[Bearbeiten | Quelltext bearbeiten]
<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

[Bearbeiten | Quelltext bearbeiten]
<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

[Bearbeiten | Quelltext bearbeiten]
if(ApplicationCommands.Cut.CanExecute(param))
{
    ApplicationCommands.Cut.Execute(param, textBox);
}

Custom Routed Commands

[Bearbeiten | Quelltext bearbeiten]
  • 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;
}