Reputation: 221
I have a canvas, which, upon a click on the left button of the mouse, has a label created on it in the clicking point. This is the xaml code:
public partial class MainWindow : Window
{
int num = 1;
List <Label> countries = new List<Label>();
public MainWindow()
{
InitializeComponent();
}
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var point = Mouse.GetPosition(Canvas);
Label label = new Label() { Width = 100, Height = 100 };
Canvas.Children.Add(label);
Canvas.SetLeft(label, point.X);
Canvas.SetTop(label, point.Y);
label.Focus();
num++;
countries.Add(label);
}
}
I would like to make it so two different labels would not be able to intersect with each other. The idea is that if the user tries to create a label in a location which would cause it to intersect with another existing label, a message box would pop and tell him to choose another location.
Unfortunately I did not succeed in implementing this. If anyone could help, I would be very glad. Help will be much appreciated :)
Upvotes: 2
Views: 99
Reputation: 189
Try this:
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var point = Mouse.GetPosition(canvas);
Rect newrect = new Rect(point.X, point.Y, 100, 100);
Boolean isIntersects = false;
foreach (Control control in canvas.Children)
{
if (control is Label)
{
Rect oldrect = new Rect(Canvas.GetLeft(control), Canvas.GetTop(control), control.Width, control.Height);
if (newrect.IntersectsWith(oldrect))
{
MessageBox.Show("Oops. Intersecting...");
isIntersects = true;
break;
}
}
}
if (isIntersects == false)
{
Label label = new Label() { Width = 100, Height = 100 };
label.Content = "This is a label:)";
label.Background = new SolidColorBrush(Colors.Yellow);
canvas.Children.Add(label);
Canvas.SetLeft(label, point.X);
Canvas.SetTop(label, point.Y);
}
}
Upvotes: 1