我有以下问题,我想通过按钮点击生成一个小画布,生成后我想通过按键事件移动它但我无法在事件中看到画布。我怎样才能看到它? (在WPF的源代码中不在XAML中)
public void Button_Click_1(object sender, RoutedEventArgs e)
{
Canvas c = new Canvas();
c.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
c.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
c.Loaded += c_Loaded;
Grid.Children.Add(c);
Canvas ship = new Canvas();
ship.Background = Brushes.Aquamarine;
ship.Height = 30;
ship.Width = 30;
ship.KeyDown += ship_KeyDown;
Canvas.SetTop(ship, 50);
c.Children.Add(ship);
}
void ship_KeyDown(object sender, KeyEventArgs e)
{
canvas.Setleft(ship, canvas.Getleft(ship) +10); //here i can not see the object "ship" :(
}
答案 0 :(得分:2)
使用参数sender:
Canvas ship = (Canvas) sender;
答案 1 :(得分:0)
您需要添加c或运送到layoutroot`
答案 2 :(得分:0)
最简单的方法是将其添加到<list>
UIElement
并使用foreach
- 循环修改