Timo Müller
Timo Müller

Reputation: 13

Add A TextBox To A WPF-Canvas Programmatically

I want to add a TextBox to a WPF-Canvas. But if I execute the Program, nothing happens. Some ideas, clues, etc?

Here my Code-behind:

private void Main_Canvas_KeyUp(object sender, KeyEventArgs e)
{
   if (e.Key == Key.Enter)
   {
       TextBox textBox = new TextBox();
       textBox.Width = 250;
       Canvas.SetLeft(textBox, Main_Canvas.Width / 2);
       Canvas.SetTop(textBox, Main_Canvas.Height / 2);
       Main_Canvas.Children.Add(textBox);
    }
}

Here my XAML:

<Canvas x:Name="Main_Canvas" KeyUp="Main_Canvas_KeyUp" />

Upvotes: 1

Views: 1416

Answers (1)

Avestura
Avestura

Reputation: 1557

That's because your canvas doesn't have the focus. Set it's Focusable to true and make sure that has focus with calling Focus() in windows Loaded event.

Xaml:

<Canvas x:Name="Main_Canvas" KeyUp="Main_Canvas_KeyUp" Focusable="True" />

Window Loaded event handler:

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
        Main_Canvas.Focus();
 }

Upvotes: 2

Related Questions