Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

Tuesday, May 18, 2010

Closing a window or dialog box when an escape key is pressed in WPF

When you pop up a dialog box, users expect to be able to press the ESC key to close the dialog box. It can be quite annoying otherwise. In WPF, the easiest way to do that is to set the IsCancel property of your close button like this:

<Button Content="Close" Click="OnClose" IsCancel="True" />

On a recent project, however, I did not have a close button to set IsCancel on. The solution is to use WPF commands and input gestures. Here is an example:

<Window.CommandBindings>
   <CommandBinding Command="Close" Executed="OnCloseCmdExecuted" />
</Window.CommandBindings>

<Window.InputBindings>
   <KeyBinding Command="Close" Key="Escape" />
</Window.InputBindings>

private void OnCloseCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
   this.Close();
}

Wednesday, February 10, 2010

WPF menus that go up

I needed a menu docked to the bottom of an application's window. Docking to the bottom of the window is no problem. However, it did not work well, because by default, WPF menus drop down. I needed it to drop up. I need behavior like the Windows Start menu when it is docked on the bottom of the workspace. I looked for a PopupDirection or some such property -- no luck.

I found a solution.

Using Blender, edit a copy of a menu's ItemContainerStyle. The default style has two Popup elements with a Placement property. Placement = "Top" is a valid option.