C# – How to reuse WPF ScrollViewer to create the own scrollable control

cnetscrollviewwpf

I'm trying to improve the graph drawing control that comes with Graph#. It's good, but things get out of hand when you start dragging nodes around. This is my first encounter with WPF, so this is probably a newbie question. 🙂

I have the GraphCanvas control which has nodes and edges on it. They can be dragged around which changes their coordinates, possibly making them negative. I would like to add scrollbars to the control which would allow to see how big the canvas really is.

To this end I'm thinking of putting the GraphCanvas inside a ScrollViewer. Which would be pretty easy and straightforward if not for one problem. I may not resize the GraphCanvas itself when a node is dragged outside the borders or this will mess up dragging bad. That is also the problem with the original control (check it out, it comes with a sample application).

It would be good if I could bind the scrollbar size/location to properties of the GraphCanvas, so that the ScrollViewer would not scroll anything physically, but just set the properties of GraphCanvas. That in turn would perform all actual calculations and scrolling.

How can this be done?

Best Answer

OK, I found it! Three easy steps:

  1. Implement System.Windows.Controls.Primitives.IScrollInfo on your custom control;
  2. Add your custom control to a ScrollViewer;
  3. Set the CanContentScroll property on the ScrollViewer to True.

Voila!