[WPF] HotkeyEditBox
От: Vladek Россия Github
Дата: 14.07.11 14:56
Оценка: 11 (2)
#Имя: FAQ.dotnet.gui.wpf.HotkeyEditBox
Здравствуйте, DeKo, Вы писали:

DK>Здравствуйте!

DK>Существует ли готовый контрол для редактирования Хоткеев в WPF?
DK>Или же ручками эдитБокс + PreviewKeyDown ?

Вроде работал нормально:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

public class ShortcutKeyBox : TextBox
{
    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        try
        {
            if (e.Key == Key.LeftCtrl ||
                e.Key == Key.RightCtrl ||
                e.Key == Key.LeftAlt ||
                e.Key == Key.RightAlt ||
                e.Key == Key.LeftShift ||
                e.Key == Key.RightShift ||
                e.Key == Key.System ||
                e.Key == Key.Escape ||
                e.Key == Key.Tab ||
                e.Key == Key.Return)
                return;

            e.Handled = true;

            try
            {
                var newKeyGesture = new KeyGesture(e.Key, Keyboard.Modifiers);

                if (newKeyGesture.Key == Key.Back &&
                    newKeyGesture.Modifiers == ModifierKeys.None &&
                    KeyGesture.Key == Key.Back &&
                    KeyGesture.Modifiers == ModifierKeys.None)
                {
                    KeyGesture = null;
                }
                else
                {
                    KeyGesture = newKeyGesture;
                }
            }
            catch (NotSupportedException)
            {
            }
        }
        finally
        {
            base.OnPreviewKeyDown(e);
        }
    }

    public KeyGesture KeyGesture
    {
        get { return (KeyGesture)GetValue(KeyGestureProperty); }
        set 
        { 
            SetValue(KeyGestureProperty, value);
        }
    }

    public static readonly DependencyProperty KeyGestureProperty =
        DependencyProperty.Register("KeyGesture", typeof(KeyGesture), typeof(ShortcutKeyBox),
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                OnKeyGesturePropertyChanged, OnKeyGesturePropertyCoerceValue,
                true, UpdateSourceTrigger.PropertyChanged));

    private static void OnKeyGesturePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var self = (ShortcutKeyBox)d;
        var keyGesture = e.NewValue as KeyGesture;
        if (keyGesture == null)
            self.Text = String.Empty;
        else
            self.Text = keyGesture.GetDisplayStringForCulture(CultureInfo.CurrentCulture);
    }

    private static object OnKeyGesturePropertyCoerceValue(DependencyObject d, object baseValue)
    {
        return baseValue;
    }
}
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.