tags:

views:

151

answers:

1

I've been playing with WPF/XAML again and have noticed that there doesn't seem to be an easy way to code UI-only keygestures/mousegestures and the like. For example, how to add a "Maximize without windowframe" command to a window.

Currently this involves code not unlike this in code-behind:

  public partial class MainWindow : Window {
    public static RoutedUICommand Maximize = new RoutedUICommand("Maximizes window.", "Maximize", typeof(MainWindow));

    public MainWindow() {
      Loaded += MainWindow_AddCommands;
      InitializeComponent();
    }

    void MainWindow_AddCommands(object sender, RoutedEventArgs e) {
      var CanExecuteMaximize = new CanExecuteRoutedEventHandler((obj, args) => {
        if (!(WindowState == WindowState.Minimized))
          args.CanExecute = true;
        else
          args.CanExecute = false;
      });

      var ExecutedMaximize = new ExecutedRoutedEventHandler((obj, args) => {
        switch (WindowStyle) {
          case WindowStyle.None:
            WindowStyle = WindowStyle.SingleBorderWindow;
            break;
          case WindowStyle.SingleBorderWindow:
            WindowStyle = WindowStyle.None;
            break;
          default:
            break;
        }
        switch (WindowState) {
          case WindowState.Maximized:
            WindowState = WindowState.Normal;
            break;
          case WindowState.Minimized:
            throw new InvalidOperationException();
          case WindowState.Normal:
            WindowState = System.Windows.WindowState.Maximized;
            break;
          default:
            break;
        }
      });

      CommandBindings.Add(new CommandBinding(Maximize, ExecutedMaximize, CanExecuteMaximize));
    }
  }

And this in XAML:

  <Window.InputBindings>
    <KeyBinding Command="{x:Static local:MainWindow.Maximize}" Gesture="F11"/>
  </Window.InputBindings>

But this seems entirely backward. The code-behind shouldn't be handling the UI at all! It seems like this can be partially mitigated by creating a dependency property instead and using EventTriggers, but that still puts some code behind that doesn't seem like it should be there.

Is there any way to do a proper F11-maximize without code behind?

+2  A: 

The answers to this question provide a couple options: keyboard-events-in-a-wpf-mvvm-application

Eric Dahlvang
Thanks Eric, there's definitely some good stuff there but I'd like to see if anyone has a solution that uses just XAML. After all, this is entirely a UI thing and shouldn't be dependent on the code behind. At the bare minimum, I'd like the code behind to be generic enough that I could later add an "F6 key makes the border thicker on the currently selected element" without having to rewrite my code behind again.So I guess what I'm asking is, is there a Trigger type that can fire on key presses?