Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ContentDialog: Keyboard "navigation" (Enter for Primary, Escape for Close) #95

Open
gentledepp opened this issue Dec 9, 2024 · 0 comments

Comments

@gentledepp
Copy link

Hello!

It would be very helpful to - out of the box - be able to

  1. accept any ContentDialog (i.e. ContentDialogResult.Primary) by pressing Enter (or have some binding that allows to define which key to press) and
  2. being able to cancel any ContentDialog by pressing Escape

This does work if I

  • add my own focusable content
  • add event handlers to it
  • and make sure it is focused

I would also be happy if we could subscribe to the KeyDown event of the ContentDialog

However, on Windows, the KeyDown event is never fired.

Here is my sample that actually works but is a bit complicated IMHO

// for strings, we need to add a TextBlock, since the DataTempalte for strings is - by default - a non-focusable TextBlock
var tb = new TextBlock
{
    Text = message,
    Focusable = true, // set it to focusable
    IsTabStop = true // and a tab stop
};
var d = new ContentDialog()
{
    Title = title,
    Content = tb,
    IsSecondaryButtonEnabled = false,
    PrimaryButtonText = okButton,
    CloseButtonText = cancelButton,
};
// ...subscribe to the keydown events of the _TextBlock_ (!!)
tb.KeyDown += (_, args) =>
{
    if (args.Key == Key.Enter)
        d.Hide(ContentDialogResult.Primary);
    if (args.Key == Key.Escape)
        d.Hide();
};
// ... and ensure that it is focused when it is attached to the view
tb.AttachedToVisualTree += (element, args) =>
{
    if (element is IInputElement i)
        i.Focus();
};

var r = await d.ShowAsync();

I would prefer this though:

var d = new ContentDialog()
{
    Title = title,
    Content = message,
    IsSecondaryButtonEnabled = false,
    PrimaryButtonText = okButton,
    CloseButtonText = cancelButton,
};
// ...subscribe to the keydown events of the ContentDialog
d.KeyDown += (_, args) =>
{
    if (args.Key == Key.Enter)
        d.Hide(ContentDialogResult.Primary);
    if (args.Key == Key.Escape)
        d.Hide();
};

var r = await d.ShowAsync();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant