简体   繁体   中英

Wpf Dependency Property Dynamic Key Down

I don't know if my title is proper.

But what i am doing here is I am creating a Program that draw rectangle on canvas.

As of now i can draw on canvas by triggering a dependency property when i press the SHIFT key on keyboard. But i want it to become dynamic. I create another Dependency Property then on my XAML i can pass the KEY

something like this on my XAML

DrawingTrigger="Ctrl+Shift"

As of now this is my class

class WindowHelper : Behavior<Window>
    {


        public bool IsDrawing
        {
            get { return (bool)GetValue(IsDrawingProperty); }
            set { SetValue(IsDrawingProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsDrawing.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsDrawingProperty =
            DependencyProperty.Register("IsDrawing", typeof(bool), typeof(WindowHelper),
                new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null));

        protected override void OnAttached()
        {
            AssociatedObject.KeyDown += AssociatedObject_KeyDown;
            AssociatedObject.KeyUp += AssociatedObject_KeyUp;

            base.OnAttached();
        }

        private void AssociatedObject_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
                IsDrawing = false;
        }

        private void AssociatedObject_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
                IsDrawing = true;


        }

        protected override void OnDetaching()
        {
            AssociatedObject.KeyDown -= AssociatedObject_KeyDown;
            AssociatedObject.KeyUp -= AssociatedObject_KeyUp;
            base.OnDetaching();
        }


    }

And upon searching i found a code that print the Keyboard Modifiers pressed

            Console.WriteLine(Keyboard.Modifiers);

With the Keyboard Modifier. When i pressed the Ctrl+Shift+Alt

it gives me

Alt, Control, Shift

With this how can i use this to solve my problem?

Is it a good practice to check if each word in the DrawingTrigger is found the set the IsDrawing into True or any suggestion.

Key and Modifiers are two different things. I'd just add / remove a KeyBinding object on the Window.InputBindings. It'll handle 99% of your work for you. It already supports combining modifiers with + and handling left and right keys, etc. You just define pass Ctrl+Shift into the Modifers for example and give it an ICommand to call back into. Easy peazy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM