简体   繁体   中英

Adding basic events to dynamically added controls

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?

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);
}

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