I have an observable collection of line segments specified by its boundary points. How can I bind it to draw the lines on a canvas?
I have seen the solution for shapes using only one point to define the position. But for applying this approach to lines it need awkward precomputations on coordinates to get the position of outer rectangle and make line coordinates relative to it. Is there a way to avoid it?
Here is an example how you could do it:
The line is defined as follows:
MainWindow.xaml:
MainWindow.xaml.cs:
In the above example, the lines are static, i.e. if you update the
From
andTo
positions, the UI will not update. If you want the UI to update, you must implementINotifyPropertyChanged
for theLine
class.This sample shows a window that looks like this:
As an aside, what I often do to avoid the ItemsControl is to use PolyLine and simply bind a collection of points. In the XAML:
Your code would simply be a PointCollection:
I find the ItemsControl will not work in some instances. Perhaps a defect in the WPF or something I don't understand. It is certainly more complicated than simple binds which can achieve the same results.
One thing to keep in mind is that you can't just add points to the already bound control and perform a NotifyPropertyChanged and expect it to work. You have to actually set an entirely new PointCollection. You can copy the old PointCollection to the new one via a constructor so it isn't much of a hassle.