In GDI+/WinForms, I could do this in the Click() event and using the graphics Object:
AddPoint(p); //Add Point contains some code to make sure there is only 3 dots
foreach (Point p in PointList) {
DrawRectangle(p);
}
Invalidate();
If I try something similar in WPF, it won’t cleanup the dots I created (I’m guessing because of how WPF works). What this means is if I check to make sure there is only three dots at a time, and pop off the oldest point to make room for the new one, the rectangle drawn would be still there.
So the question is, how can I create something in WPF that allows me to
- Draw a rectangle at a Point
- Remove rectangles/points from a WPF canvas after there is more than 3
You’re doing WPF the WinForms way. Don’t do that. It’s like writing VB code in C++. It can only end in tears.
To do this the WPF way, use databinding and a view model class to do the logic of “no more than 3 at a time.” Then, for the UI, just bind to the PointList in your view model.
Here’s what my XAML should look like. Notice I’m just using an ItemsControl and a Canvas, then binding the ItemsSource to PointList:
Then we just need to create the PointList. We’ll use the normal WPF means: a view model class to hold the point list:
Piece of cheese, yeah? So the final part is just telling the XAML to load your view model. Inside the the code-behind for your XAML, set the DataContext to your view model:
Now that you’ve got that in place, you can add/remove rectangles anywhere in your code simply by calling viewModel.AddPoint or viewModel.PointList.Remove, and the UI will automatically update to reflect the changes.