I'm making a project where I create the whole project (including the template) with C# on Visual Studio.
I've made the template and have just begun to work on the Events, I want to make an event MouseLeftButtonDown for a Canvas I created, this event will log the mouse position.
This is my code:
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);
}
And this is my Event:
private void canvas1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
down1 = e.GetPosition(canvas1);
}
}
}
I've tried to do down1 = e.GetPosition(canvas1); but I'm getting an error on (canvas1); "The name canvas1 does not exist in the current context"
I've made a similar project without having to code the template, with no problems whatsoever..
but I'm getting an error on (canvas1);
That is because canvas1 is a local variable of another method, not accessible inside canvas1_MouseLeftButtonDown().
You can use:
Canvas c = sender as Canvas; // or Canvas c = (Canvas) sender;
down1 = e.GetPosition(c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With