为什么我无法从事件处理程序中访问变量?

时间:2011-01-07 16:45:02

标签: c# wpf event-handling

我正在创建一个项目,我用Visual Studio上的C#创建整个项目(包括模板)。

我已经制作了模板并且刚刚开始处理事件,我想为我创建的Canvas创建一个事件MouseLeftButtonDown,此事件将记录鼠标位置。

这是我的代码:

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private char tester;
        private Point down1;
        private Point up1;

        private void Grid1_Loaded(object sender, RoutedEventArgs e)
        {
            RowDefinition row1 = new RowDefinition();
            RowDefinition row2 = new RowDefinition();

            row1.Height = new GridLength(40);
            row2.Height = new GridLength(1, GridUnitType.Star);

            Grid1.RowDefinitions.Add(row1);
            Grid1.RowDefinitions.Add(row2);

            Canvas canvas1 = new Canvas();
            canvas1.Background = new SolidColorBrush(Colors.Beige);
            Grid.SetRow(canvas1, 1);
            Grid1.Children.Add(canvas1);
            canvas1.MouseLeftButtonDown += new RoutedEventHandler(canvas1_MouseLeftButtonDown);
            canvas1.MouseLeftButtonUp += new RoutedEventHandler(canvas1_MouseLeftButtonUp);


            Button btnRect = new Button();
            btnRect.Content = "Rectangulo";
            btnRect.Margin = new Thickness(5, 5, 5, 5);
            btnRect.HorizontalAlignment = HorizontalAlignment.Left;
            btnRect.VerticalAlignment = VerticalAlignment.Center;
            Grid.SetRow(btnRect, 0);
            Grid1.Children.Add(btnRect);
            //btnRect.Click += new RoutedEventHandler(btnRect_Click);

            Button btnEllip = new Button();
            btnEllip.Content = "Ellipse";
            btnEllip.Margin = new Thickness(75, 5, 5, 5);
            btnEllip.HorizontalAlignment = HorizontalAlignment.Left;
            btnEllip.VerticalAlignment = VerticalAlignment.Center;
            Grid.SetRow(btnEllip, 0);
            Grid1.Children.Add(btnEllip);
            //btnEllip.Click += new RoutedEventHandler(btnEllip_Click);

        }

这是我的活动:

private void canvas1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                 down1 = e.GetPosition(canvas1); 
            }
        }
    }

我试过down1 = e.GetPosition(canvas1);,但我在(canvas1)上收到错误; “名称canvas1在当前上下文中不存在”

我做了一个类似的项目,无需编写模板,没有任何问题..

5 个答案:

答案 0 :(得分:2)

  

但我在(canvas1)上遇到错误;

这是因为canvas1是另一个方法的局部变量,不能在canvas1_MouseLeftButtonDown()内访问。

您可以使用:

 Canvas c = sender as Canvas;  // or Canvas c = (Canvas) sender;
 down1 = e.GetPosition(c); 

答案 1 :(得分:0)

您在Grid1_Loaded方法中将canvas1声明为局部变量。将它在类中定义为成员变量,它应该可以工作。

答案 2 :(得分:0)

怎么样:

down1 = e.GetPosition((Canvas)sender); 

答案 3 :(得分:0)

问题是canvas1是Grid1_Loaded中的局部变量。无法在该方法之外访问该变量。

答案 4 :(得分:0)

问题是canvas1不在范围内。你可以像这样内联一个简单的lambda表达式:

canvas1.MouseLeftButtonDown += (sender, e) => down1 = e.GetPosition(canvas1);