Last Update

  • Zoombox (new)
  • Rubberband Adorner (updated)

    Introduction

    In the first article of this series, I have shown you how to move, resize and rotate items on a canvas. This time we are going to add further features that are essential for a typical diagram designer:

  • Designer Canvas (variable size, scrollable)

  • Zoombox
  • Rubberband selection
  • Keystroke selection (LeftMouseButton + Ctrl)
  • Toolbox (drag & drop)
  • Rotate items (left, right)

    Designer Canvas

    In the previous article, you probably have noticed that when you move an item outside the borders of the DesignerCanvas the item is no longer accessible. Normally you would expect that the designer application provides scroll bars so that you can easily scroll to any item outside the visible canvas region. For this I thought I just have to wrap the DesignerCanvas into a ScrollViewer, but that didn’t work. I soon found the reason for this behaviour; let me explain it with the following code snippet:
    Hide Copy Code
    <Canvas Width=”200”

    1. Height="200"
    2. Background="WhiteSmoke"><br /> <Rectangle Fill="Blue"
    3. Width="100"
    4. Height="100"
    5. Canvas.Left="300"
    6. Canvas.Top="300" /><br /></Canvas><br />Here I have placed a `Rectangle` object on a `Canvas`, but positioned it outside the boundaries of the `Canvas`. Will this change the size of the `Canvas`? Of course not, the `Canvas` will keep its size, no matter where you place an item.<br />For the `DesignerCanvas` this means that it will keep its size, even if you drag an item far beyond the borders of the canvas. Now we understand why a `ScrollViewer` doesn't help: the `DesignerCanvas` will never notify the `ScrollViewer` of a size change, just because there is none.<br />The solution is that we must force the `DesignerDanvas` to adjust its size everytime an item is moved or resized. Fortunately the `Canvas` class provides an overrideable method named `MeassureOverride` that allows the `DesignerCanvas` to calculate its desired size and return it to the WPF layout system. The calculation is quite simple as you can see here:<br />Hide Copy Code<br />protected override Size MeasureOverride(Size constraint)<br />{<br /> Size size = new Size();<br /> foreach (UIElement element in base.Children)<br /> {<br /> double left = Canvas.GetLeft(element);<br /> double top = Canvas.GetTop(element);<br /> left = double.IsNaN(left) ? 0 : left;<br /> top = double.IsNaN(top) ? 0 : top;
    7. _//measure desired size for each child_<br /> element.Measure(constraint);
    8. Size desiredSize = element.DesiredSize;<br /> if (!double.IsNaN(desiredSize.Width) && !double.IsNaN(desiredSize.Height))<br /> {<br /> size.Width = Math.Max(size.Width, left + desiredSize.Width);<br /> size.Height = Math.Max(size.Height, top + desiredSize.Height);<br /> }<br /> }<br /> _//for aesthetic reasons add extra points_<br /> size.Width += 10;<br /> size.Height += 10;<br /> return size;<br />}

    DesignerItem

    The DesignerItemis inherited from ContentControl, so that we can reuse the ControlTemplate of our first article. The DesignerItem provides an IsSelected property to indicate if it is selected or not:
    Hide Copy Code
    public class DesignerItem : ContentControl
    {
    public bool IsSelected
    {
    get { return (bool)GetValue(IsSelectedProperty); }
    set { SetValue(IsSelectedProperty, value); }
    }
    public static readonly DependencyProperty IsSelectedProperty =
    DependencyProperty.Register(“IsSelected”, typeof(bool),
    typeof(DesignerItem),
    new FrameworkPropertyMetadata(false));
    …

}
Then we have to implement an event handler for the MouseDown event to support multiple selection of items:
Hide Copy Code
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
base.OnPreviewMouseDown(e);
DesignerCanvas designer = VisualTreeHelper.GetParent(this) as DesignerCanvas;

  1. if (designer != null)<br /> {<br /> if ((Keyboard.Modifiers & <br /> (ModifierKeys.Shift | ModifierKeys.Control)) != ModifierKeys.None)<br /> {<br /> this.IsSelected = !this.IsSelected;<br /> }<br /> else<br /> {<br /> if (!this.IsSelected)<br /> {<br /> designer.DeselectAll();<br /> this.IsSelected = true;<br /> }<br /> }<br /> }
  2. e.Handled = false;<br />}<br />Please note that we handle the `PreviewMouseDown` event, which is the tunnelling version of the `MouseDown` event and that we mark the event as not handled. The reason is that we want the item to be selected even if the `MouseDown` event is targeting another `Control` inside the `DesignerItem`; e.g. take a look at a class diagram in Visual Studio, if you click on the `ToggleButton` of the `Expander`, the item becomes selected **and** the `Expander` toggles its size, both at the same time.<br />Finally we have to update the template for the `DesignerItem` such that the resize decorator is only visible when the `IsSelected` property is `true`, which can be handled with a simple `DataTrigger`:<br />Hide Shrink ![](https://cdn.nlark.com/yuque/0/2020/png/137527/1582016073396-d83f471b-52ac-444d-9a1f-478968719225.png#align=left&display=inline&height=16&originHeight=16&originWidth=16&size=0&status=done&style=none&width=16) Copy Code<br /><Style TargetType="{x:Type s:DesignerItem}"><br /> <Setter Property="MinHeight" Value="50"/><br /> <Setter Property="MinWidth" Value="50"/><br /> <Setter Property="SnapsToDevicePixels" Value="true"/><br /> <Setter Property="Template"><br /> <Setter.Value><br /> <ControlTemplate TargetType="{x:Type s:DesignerItem}"><br /> <Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent},<br /> Path=.}"><br /> <s:MoveThumb<br /> x:Name="PART_MoveThumb"<br /> Cursor="SizeAll"<br /> Template="{StaticResource MoveThumbTemplate}" /><br /> <ContentPresenter<br /> x:Name="PART_ContentPresenter"<br /> Content="{TemplateBinding ContentControl.Content}"<br /> Margin="{TemplateBinding Padding}"/><br /> <s:ResizeDecorator x:Name="PART_DesignerItemDecorator"/><br /> </Grid><br /> <ControlTemplate.Triggers><br /> <Trigger Property="IsSelected" Value="True"><br /> <Setter TargetName="PART_DesignerItemDecorator"<br /> Property="ShowDecorator" Value="True"/><br /> </Trigger><br /> </ControlTemplate.Triggers><br /> </ControlTemplate><br /> </Setter.Value><br /> </Setter><br /></Style>

Toolbox

The Toolbox is an ItemsControl that uses the ToolboxItem class as default container to display its items. For this we have to override the GetContainerForItemOverride method and the IsItemItsOwnContainerOverride method:
Hide Copy Code
public class Toolbox : ItemsControl
{
private Size defaultItemSize = new Size(65, 65);
public Size DefaultItemSize
{
get { return this.defaultItemSize; }
set { this.defaultItemSize = value; }
}

  1. protected override DependencyObject GetContainerForItemOverride()<br /> {<br /> return new ToolboxItem();<br /> }
  2. protected override bool IsItemItsOwnContainerOverride(object item)<br /> {<br /> return (item is ToolboxItem);<br /> }<br />}<br />Additionally we want the `Toolbox` to use a `WrapPanel` to layout its items:<br />Hide Copy Code<br /><Setter Property="ItemsPanel"><br /> <Setter.Value><br /> <ItemsPanelTemplate><br /> <WrapPanel Margin="0,5,0,5"
  3. ItemHeight="{Binding Path=DefaultItemSize.Height,<br /> RelativeSource={RelativeSource AncestorType=s:Toolbox}}"
  4. ItemWidth="{Binding Path=DefaultItemSize.Width,<br /> RelativeSource={RelativeSource AncestorType=s:Toolbox}}"/><br /> </ItemsPanelTemplate><br /> </Setter.Value><br /></Setter><br />Note that the `ItemHeight` and `ItemWidth` properties of the `WrapPanel` are bound to the `DefaultItemSize` property of the `Toolbox`.

ToolboxItem

The ToolboxItem is the place where drag operations are actually started if you want to drag an item from the toolbox and drop it on the canvas. There is nothing mysterious about drag and drop itself, but still you have to take care how to copy an item from the drag source (Toolbox) to the drop target (DesignerCanvas). In our case we use the XamlWriter.Save method to serialize the content of the ToolboxItem into XAML, although that kind of serialization has some notable limitations in exactly what is serialized. In a later article, we will switch to binary serialization.
Hide Shrink WPF Diagram Designer - Part 2 - 图1 Copy Code
public class ToolboxItem : ContentControl
{
private Point? dragStartPoint = null;

static ToolboxItem()<br />    {<br />        FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolboxItem),<br />               new FrameworkPropertyMetadata(typeof(ToolboxItem)));<br />    }

protected override void OnPreviewMouseDown(MouseButtonEventArgs e)<br />    {<br />        base.OnPreviewMouseDown(e);<br />        this.dragStartPoint = new Point?(e.GetPosition(this));<br />    }

protected override void OnMouseMove(MouseEventArgs e)<br />    {<br />        base.OnMouseMove(e);<br />        if (e.LeftButton != MouseButtonState.Pressed)<br />        {<br />            this.dragStartPoint = null;<br />        }<br />        if (this.dragStartPoint.HasValue)<br />        {<br />            Point position = e.GetPosition(this);<br />            if ((SystemParameters.MinimumHorizontalDragDistance <=<br />                 Math.Abs((double)(position.X - this.dragStartPoint.Value.X))) ||<br />                 (SystemParameters.MinimumVerticalDragDistance <=<br />                 Math.Abs((double)(position.Y - this.dragStartPoint.Value.Y))))<br />            {<br />                string xamlString = XamlWriter.Save(this.Content);<br />                DataObject dataObject = new DataObject("DESIGNER_ITEM", xamlString);

            if (dataObject != null)<br />                {<br />                    DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Copy);<br />                }<br />            }<br />            e.Handled = true;<br />        }<br />    }<br />}

Rubberband Selection

When the user initiates a drag operation directly on the DesignerCanvas, a new instance of a RubberbandAdorner is created:
Hide Shrink Copy Code
public class DesignerCanvas : Canvas
{
…

protected override void OnMouseMove(MouseEventArgs e)<br />    {<br />        base.OnMouseMove(e);

    if (e.LeftButton != MouseButtonState.Pressed)<br />            this.dragStartPoint = null;

    if (this.dragStartPoint.HasValue)<br />        {<br />            AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(this);<br />            if (adornerLayer != null)<br />            {<br />                RubberbandAdorner adorner = new RubberbandAdorner(this, dragStartPoint);<br />                if (adorner != null)<br />                {<br />                    adornerLayer.Add(adorner);<br />                }<br />            }<br />            <br />            e.Handled = true;<br />        }        <br />    }<br />    <br />    ...<br />}<br />As soon as the `RubberbandAdorner` is created, it takes control over the drag operation and updates the drawing of the rubber band and the current selection of items. These updates happen inside the `UpdateRubberband()` and `UpdateSelection()` methods:<br />Hide   Copy Code<br />public class RubberbandAdorner : Adorner<br />{    <br />    ....<br />    <br />    private Point? startPoint, endPoint;

protected override void OnMouseMove(MouseEventArgs e)<br />    {<br />        if (e.LeftButton == MouseButtonState.Pressed)<br />        {<br />            if (!this.IsMouseCaptured)<br />            {<br />                this.CaptureMouse();<br />            }

        this.endPoint = e.GetPosition(this);<br />            this.UpdateRubberband();<br />            this.UpdateSelection();<br />            e.Handled = true;<br />        }<br />    }<br />    <br />    ...<br />}<br />Since the actual rubber band is an instance of a `Rectangle` class, the `UpdateRubberband()` method just needs to update the size and the position of that `Rectangle`:<br />Hide   Copy Code<br />private void UpdateRubberband()<br />{<br />    double left = Math.Min(this.startPoint.Value.X, this.endPoint.Value.X);<br />    double top = Math.Min(this.startPoint.Value.Y, this.endPoint.Value.Y);

double width = Math.Abs(this.startPoint.Value.X - this.endPoint.Value.X);<br />    double height = Math.Abs(this.startPoint.Value.Y - this.endPoint.Value.Y);

this.rubberband.Width = width;<br />    this.rubberband.Height = height;<br />    Canvas.SetLeft(this.rubberband, left);<br />    Canvas.SetTop(this.rubberband, top);<br />}<br />A little more work needs to be done in the `UpdateSelection() `method. Here we check for each `DesignerItem` if it is contained in the current rubber band. For this, the `VisualTreeHelper.GetDescendantBounds(item)` method provides us the bounding rectangle for each item. We transform the coordinates of this rectangle to the `DesignerCanvas` and call the `rubberband.Contains(itemBounds)` method to decide whether the item is selected or not!<br />Hide   Copy Code<br />private void UpdateSelection()<br />{<br />    Rect rubberBand = new Rect(this.startPoint.Value, this.endPoint.Value);<br />    foreach (DesignerItem item in this.designerCanvas.Children)<br />    {<br />        Rect itemRect = VisualTreeHelper.GetDescendantBounds(item);<br />        Rect itemBounds = item.TransformToAncestor<br />   (designerCanvas).TransformBounds(itemRect);

    if (rubberBand.Contains(itemBounds))<br />        {<br />            item.IsSelected = true;<br />        }<br />        else<br />        {<br />            item.IsSelected = false;<br />        }<br />    }<br />}<br />Please note that these update methods are called whenever the `MouseMove` event is fired during a drag operation, and that is quite frequently! Instead you may consider to update the selection only once at the end of the drag operation, when the `MouseUp` event is fired.

Customize the DragThumb

The default style of the DragThumb class is a transparent Rectangle, but if you want to adjust that style you can do this with the help of an attached property named DesignerItem.DragThumbTemplate. Let me explain the usage with an example. Let’s say the content of a DesignerItem is a star shape like this one:
Hide Copy Code
<Path Stroke=”Red” StrokeThickness=”5” Stretch=”Fill” IsHitTestVisible=”false”

  Data="M 9,2 11,7 17,7 12,10 14,15 9,12 4,15 6,10 1,7 7,7 Z"/><br />To illustrate the result, I have colorized the default `DragThumb` template:<br />Now try the following:<br />Hide   Copy Code<br /><Path Stroke="Red" StrokeThickness="5" Stretch="Fill" IsHitTestVisible="false"

  Data="M 9,2 11,7 17,7 12,10 14,15 9,12 4,15 6,10 1,7 7,7 Z"><br />    <s:DesignerItem.DragThumbTemplate><br />         <ControlTemplate><br />            <Path Data="M 9,2 11,7 17,7 12,10 14,15 9,12 4,15 6,10 1,7 7,7 Z"

                Fill="Transparent" Stretch="Fill"/><br />         </ControlTemplate><br />    </s:DesignerItem.DragThumbTemplate><br /></Path><br />The result is a `DragThumb` that fits much better than the default one:<br />