0

I have some basic code that, when a control is dropped on a Canvas, I need the user to be able to delete said control via a simple key press.

private void PlaceElementOnCavas(UIElement element, Point point) {

    Canvas.SetLeft(element, point.X);
    Canvas.SetTop(element, point.Y);

    // Add the event to allow the user to press delete and remove the control
    element.KeyDown += (sender, e) => {
        if (e.Key == Key.Delete) {
            this.designCanvas.Children.Remove(element);
        }
    };

    this.designCanvas.Children.Add(element);

}

My code looks like that. My control is added fine, at exactly the point on the Canvas I need it do.

The event handler does nothing, whether I try to add it via a lambda or via a traditional call to another method.

What am I missing?

Patrick
  • 11
  • 3
  • 1
    What is `element`? It needs to have focus to receive `KeyDown` event and it may process `PreviewKeyDown` itself. Maybe you want to subscribe to events of container? – Sinatr Dec 06 '17 at 14:02
  • @sinatr It's a UI element as per the parameter, it can be a variety of basic controls dragged onto the designer surface. A Button, a CheckBox, a Slider, etc. – Patrick Dec 06 '17 at 14:08
  • Did you set focus to it first before pressing `Delete` key? How do you realize that *"event handler does nothing"*? Is it not executed (my thoughts) or does the child stays after `Remove()` ? Set breakpoint. – Sinatr Dec 06 '17 at 14:10
  • [Grid](https://msdn.microsoft.com/en-us/library/system.windows.controls.grid(v=vs.110).aspx) is `UIElement`, but it has exactly same [problem](https://stackoverflow.com/q/15241118/1997232) as yours. – Sinatr Dec 06 '17 at 14:12

1 Answers1

0

The following steps should be enough to make your keyboard input work:

  • Set Focusable="True"
  • Handle MouseLeftButtonUp and assign the Keyboard.Focus in it
  • Set a Background in order to capture the mouse events
  • Handle the key events

Then click into the element to focus it and use your keys. Alternative, if you don't plan to use the mouse and only want to focus it by pressing tab, you only need the Focusable and the key events.

<Grid x:Name="grid1" KeyDown="grid1_KeyDown" Focusable="True" MouseLeftButtonUp="grid1_MouseLeftButtonUp" Background="Transparent">
</Grid>

Focus handling:

private void grid1_KeyDown(object sender, KeyEventArgs e)
{
    // whatever you plan to do
}

private void grid1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Keyboard.Focus(sender as IInputElement);
}
grek40
  • 13,113
  • 1
  • 24
  • 50