0
votes

I'm launching a WPF Window (using ShowDialog) in the KeyDown handler of a Winforms TextBox. The WPF Window has a button with IsDefault = true. After pressing Enter on the TextBox, the WPF AccessKey mechanism apparently picks it up after window load and triggers the default button.

This issue is not present when launching the window from the KeyDown handler of a WPF TextBox.

Looking for a workaround that would prevent the WPF window from receiving the key press that is being handled in the Winforms textbox.

Here is some sample code that illustrates the problem:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        var window = new System.Windows.Window();
        var button = new System.Windows.Controls.Button
        {
            IsDefault = true,
            Content = "OK",
        };
        button.Click += (s, args) => window.Close();
        window.Content = button;

        // window loads then immediately closes due to the default button being triggered
        window.ShowDialog();
    }
}
2
Possibly related to this WPF access keys scoping problem? IsDefault button is registered as an access key apparently. coderelief.net/2012/07/29/wpf-access-keys-scopingO'Rooney

2 Answers

1
votes

There is probably a better way of doing this, but changing

window.ShowDialog(); 

to

Dispatcher.CurrentDispatcher.Invoke(new Action(() => window.ShowDialog()));

gave the intended behaviour for me.

0
votes

My hacky solution for now is to put in the button's command a guard condition that allows the execution of the rest of the command only if the content has been rendered (as determined by a flag set in a ContentRendered event handler). In my specific scenario (replacement message box) this works fine and it can be localized in one place but still looking for a better solution if one exists.

Update: a little sheep's solution (showing the dialog in Dispatcher.Invoke) is much cleaner.