I have a WPF Window (.NET 4.0) that opens another WPF window as a dialog using ShowDialog()
. On that dialog window I have a save and cancel button that I want to wire up alt+S and alt+C for save and cancel shortcuts respectively.
I have an AccessText
element in the buttons that display the underscore on the button for the letter following the underscore in the designer. This works when the user presses the alt key. Also the shortcut is working when the user presses the access key.
However, here are the problems:
The access key works without alt. As soon as the dialog opens I can press just the letter S or C without alt and button click event fires. If focus is on an input control (i.e. textbox) then it works only with alt, which is what I want. However, I only want the access key to work with alt when the form has focus.
After you press alt the first time, the underscores appear in the button text forever unless you start to type in an input control (i.e. textbox). I would have expected them to hide if I pressed alt again. Is this normal for WPF?
Here is the code calling the dialog from the main window:
private void Button_Click(object sender, RoutedEventArgs e)
{
var w = new DialogWindow();
w.ShowDialog();
}
Here is the XAML in the dialog window:
<Window x:Class="WpfApplication2.DialogWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="122" Width="330" Topmost="True">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Some Setting:" Margin="10"/>
<TextBox Width="200" Margin="2" />
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Name="btnSave" Margin="10,10,5,10" Width="100" Height="25" Click="btnSave_Click" >
<StackPanel Orientation="Horizontal">
<Image Source="pack://siteoforigin:,,,/save_16xLG.png" />
<AccessText Text="_Save" />
</StackPanel>
</Button>
<Button Name="btnCancel" Margin="5,10,10,10" Width="100" Height="25" Click="btnCancel_Click">
<StackPanel Orientation="Horizontal">
<Image Source="pack://siteoforigin:,,,/action_Cancel_16xLG.png" />
<AccessText Text="_Cancel" />
</StackPanel>
</Button>
</StackPanel>
</Grid>
</Window>
Here is the code behind for the dialog window:
public partial class DialogWindow : Window
{
public DialogWindow()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
this.Close();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
this.Close();
}
}