1. 程式人生 > >【WPF學習】第四十五章 視覺化物件

【WPF學習】第四十五章 視覺化物件

  前面幾章介紹了處理適量適中的圖形內容的最佳方法。通過使用幾何圖形、圖畫和路徑,可以降低2D圖形的開銷。即使正在使用複雜的具有分層效果的組合形狀和漸變畫刷,這種方法也仍然能夠正常得很好。

  然而,這樣設計不適合需要渲染大量圖形元素的繪圖密集型應用程式。例如繪圖程式、演示粒子碰撞的物理模型程式或橫向卷軸形式的遊戲。這些應用程式面臨的不是圖形複雜程度的問題,而純粹是單獨的圖形元素數量的問題。即使使用量級更輕的Geometry物件代替Path元素,需要的開銷也仍會較大地影響應用程式的效能。

  WPF針對此類問題的解決方案是,使用低階的視覺化層(visual layer)模型。基本思想是將每個圖形元素定義為一個Visual物件,Visual物件是極輕易級的要素,比Geometry物件或Path物件需要的開銷小。然後可使用單個元素在視窗中渲染所有視覺化物件。

一、繪製視覺化物件

  Visual類是抽象類,所以不能建立該類的例項。相反,需要使用繼承自Visual類的某個類,包括UIElement類(該類是WPF元素模型的根)、Viewport3DVisual類(通過該類可顯示3D內容)以及ContainerVisual類(包含其他視覺化物件的基本容器)。但最有用的派生類是DrawingVisual類,該類繼承自ContainerVisual,並添加了支援“繪製”希望放置到視覺化物件中的圖形內容的功能。

  為使用DrawingVisual類繪製內容,需要呼叫DrawingVisual.RederOpen()方法。該方法返回一個可用於定義視覺化內容的DrawingContext物件。繪製完畢後,需要呼叫DrawingContext.Close()方法。下面是繪製圖形的完整過程:

DrawingVisual visual=new DrawingVisual();
DrawingContext dc=visual.RenderOpen();

//(perform drawing here.)

dc.Close();

  在本質上,DrawingContext類由各種為視覺化物件增加了一些圖形細節的方法構成。可呼叫這些方法來繪製各種圖形、應用變換以及改變不透明度等。下表列出了DrawingContext類的方法。

   下面的示例建立了一個視覺化物件,該視覺化物件包含沒有填充的基本的黑色三角形: 

DrawingVisual visual=new DrawingVisual();
using(DrawingContext dc=visual.RenderOpen())
{
    Pen drawingPen=new Pen(Color.Black,3);
    dc.DrawLine(drawingPen,new Point(0,50),new Point(50,0));
    dc.DrawLine(drawingPen,new Point(50,0),new Point(100,50));
    dc.DrawLine(drawingPen,new Point(0,50),new Point(100,50));
}

   當呼叫DrawingContext方法,沒有實際繪製視覺化物件——而只是定義了視覺化外觀。當通過呼叫Close()方法結束繪製時,完成的圖畫被儲存在視覺化物件中,並通過只讀的DrawingVisual.Drawing屬性提供這些圖畫。WPF會儲存Drawing物件,從而當需要時可以重新繪製視窗。

  繪圖程式碼的順序很重要。後面的繪圖操作可在已經存在的圖形上繪製內容。PushXxx()方法應用的設定會被應用到後續的繪圖操作中。例如,可使用PushOpacity()方法改變不透明級別,該設定會影響所有的後續繪圖操作。可使用Pop()方法恢復最佳的PushXxx()方法。如果多次呼叫PushXxx()方法,可一次使用一系列Pop()方法呼叫關閉它們。

  一旦關閉DrawingContext物件,就不能再修改視覺化物件。但可以使用DrawingVisual類的Transform和Opacity屬性應用變換或改變整個視覺化物件的透明度。如果希望提供全新的內容,可以再次呼叫RenderOpen()方法並重復繪製過程。

二、在元素中封裝視覺化物件

  在視覺化層中編寫程式時,最重要的一步是定義視覺化物件,但為了在螢幕上實際顯示可視內容,這還不夠。為顯示視覺化物件,還需要藉助於功能完備的WPF元素,WPF元素將視覺化物件新增到視覺化樹中。乍一看,這好像降低了視覺化層變成的優點——畢竟,避免使用元素並避免它們的巨大開銷不正是使用視覺化層的全部目的嗎?然而,單個元素具有顯示任意數量視覺化物件的能力。因此,可以很容易地建立只包含一兩個元素,但卻駐留了幾千個視覺化物件的視窗。

  為在元素中駐留視覺化物件,需要執行一下任務:

  •   為元素呼叫AddVisualChild()和AddLogicalChild()方法來註冊視覺化物件。從技術角度看,為了顯示視覺化物件,不需要執行這些任務,但為了確保正確跟蹤視覺化物件,在視覺化樹和邏輯樹中顯示視覺化物件以及使用其他WPF特性(如命中測試),需要執行這些操作。
  •   重寫VisualChildrenCount屬性並返回已經增加了的視覺化物件的數量。
  •   重寫GetVisualChild()方法,當通過索引好要求視覺化物件時,新增返回視覺化物件所需的程式碼。

  當重寫VisualChildrenCount屬性和GetVisualChild()方法時,本質上時劫持了那個元素。如果使用的是能夠包含巢狀的內容控制元件、裝飾元素或面板,這些元素將不再被渲染。例如,如果在自定義視窗中重寫了這兩個方法,就看不到視窗的其他內容。只會看到新增的視覺化物件。

  因此,通常建立專用的自定義類來封裝希望顯示的視覺化物件。例如,分析下圖顯示的視窗。該視窗允許使用者為自定義的Canvas面板新增正方形(每個正方形是視覺化物件).

 

 

 

   在上圖中,視窗的左邊是具有三個RadioButton物件的工具欄。通過使用一組RadioButton物件,科室建立一套相互關聯的按鈕。當單擊這套按鈕中的某個按鈕時,該按鈕會被選中,並保持“按下”狀態,而原來選擇的按鈕會恢復成正常的外觀。

  在上圖中,視窗的右邊為自定義的名為DrawingCanvas的Canvas面板,該面板在內部儲存了視覺化物件的集合。DrawingCanvas面板返回儲存在VisualChildrenCount屬性的正方形總數量,並使用GetVisualChild()方法提供對集合中每個視覺化物件的訪問。下面是實現細節: 

 public class DrawingCanvas:Panel
    {
        private List<Visual> visuals = new List<Visual>();

        protected override Visual GetVisualChild(int index)
        {
            return visuals[index];
        }
        protected override int VisualChildrenCount
        {
            get
            {
                return visuals.Count;
            }
        }
        ...
}

  此外,DrawingCanvas類還提供了AddVisual()方法和DeleteVisual()方法,以簡化在集合的恰當位置插入視覺化物件的自定義程式碼: 

public void AddVisual(Visual visual)
        {
            visuals.Add(visual);

            base.AddVisualChild(visual);
            base.AddLogicalChild(visual);
        }

        public void DeleteVisual(Visual visual)
        {
            visuals.Remove(visual);

            base.RemoveVisualChild(visual);
            base.RemoveLogicalChild(visual);
        }

  DrawingCanvas類沒有提供用於繪製、選擇以及移動正方形的邏輯,這是因為該功能是在應用程式層中控制的。因為可能有幾個不同的繪圖工具都使用同一個DrawingCanvas類,所以這樣做是合理的。根據使用者單擊的按鈕,使用者可繪製不同型別的形狀,或使用不同的筆畫顏色和填充顏色。所有這些細節都是特定與視窗的。DrawingCanvas類提供了用於駐留、渲染以及跟蹤視覺化物件的功能。

  下面演示瞭如何在視窗的XAML標記中宣告DrawingCanvas物件: 

<local:DrawingCanvas x:Name="drawingSurface" Background="White" ClipToBounds="True"
                             MouseLeftButtonDown="drawingSurface_MouseLeftButtonDown"
                MouseLeftButtonUp="drawingSurface_MouseLeftButtonUp"
                MouseMove="drawingSurface_MouseMove"></local:DrawingCanvas>

  上圖已經分析了DrawingCanvas容器,現在應當分析建立正方形的事件處理程式碼了。首先分析MouseLeftButton事件的處理程式。正是該事件處理程式中的程式碼決定了將要執行什麼操作——是建立正方形、刪除正方形還是選擇正方形。目前,我們只對第一個任務感興趣: 

private void drawingSurface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Point pointClicked = e.GetPosition(drawingSurface);

            if (cmdAdd.IsChecked == true)
            {
                DrawingVisual visual = new DrawingVisual();
                DrawSquare(visual, pointClicked, false);
                drawingSurface.AddVisual(visual);
            }
        ...
        }

  實際工作由自定義的DrawSquare()方法執行。該方法非常有用,因為需要在程式碼中的幾個不同位置觸發正方形繪製操作。顯然,當第一次建立正方形時,需要使用DrawSquare()方法,當正方形的外觀因為各種原因發生變化時(例如,當正方形被選中時),也需要使用該方法。

  DrawSquare()方法接收三個引數:準備繪製的DrawingVisual物件、正方形左上角的點以及知識當前是否選中正方形的Boolean標誌。對於選中的正方形使用不同的填充顏色進行填充。

  下面是渲染程式碼: 

// Drawing constants.
        private Brush drawingBrush = Brushes.AliceBlue;
        private Brush selectedDrawingBrush = Brushes.LightGoldenrodYellow;
        private Pen drawingPen = new Pen(Brushes.SteelBlue, 3);
        private Size squareSize = new Size(30, 30);
        private DrawingVisual selectionSquare;

        // Rendering the square.
        private void DrawSquare(DrawingVisual visual, Point topLeftCorner, bool isSelected)
        {
            using (DrawingContext dc = visual.RenderOpen())
            {
                Brush brush = drawingBrush;
                if (isSelected) brush = selectedDrawingBrush;

                dc.DrawRectangle(brush, drawingPen,
                    new Rect(topLeftCorner, squareSize));
            }
        }

  這就是在視窗中顯示視覺化物件需要做的全部工作:渲染視覺化物件的程式碼,以及處理必需的跟蹤細節的內容。如果希望為視覺化物件新增互動功能,還需要完成其他一些工作。

三、命中測試

  繪製正方形的應用程式不僅允許繪製正方形,還允許使用者移動和刪除以及繪製的正方形。為了執行這些任務,需要編寫程式碼以截獲滑鼠單擊,並查詢位於可單擊位置的視覺化物件。該任務被稱為命中測試(hit testing)。

  為支援命中測試,最好為DrawingCanvas類新增GetVisual()方法。該方法使用一個點作為引數並返回匹配的DrawingVisual物件。為此使用了VisualTreeHelper.HitTest()靜態方法。下面是GetVisual()方法的完整帶程式碼: 

public DrawingVisual GetVisual(Point point)
        {
            HitTestResult hitResult = VisualTreeHelper.HitTest(this, point);
            return hitResult.VisualHit as DrawingVisual;
        }

  在該例中,程式碼忽略了所有非DrawingVisual型別的命中物件,包括DrawingCanvas物件本身。如果沒有正方形被單擊,GetVisual()方法返回null引用。

  刪除功能利用了GetVisual()方法。當選擇刪除命令並選中一個正方形時,MouseLeftButtonDown事件處理程式使用下面的程式碼刪除這個正方形: 

else if (cmdDelete.IsChecked == true)
            {
                DrawingVisual visual = drawingSurface.GetVisual(pointClicked);
                if (visual != null) drawingSurface.DeleteVisual(visual);
            }

  可用類似的程式碼支援拖放特性,但需要通過一種方法對拖動進行跟蹤。在視窗中添加了三個欄位用於該目的——isDragging、clickOffset和selectedVisual: 

 // Variables for dragging shapes.
        private bool isDragging = false;
        private Vector clickOffset;
        private DrawingVisual selectedVisual;

 當用戶單擊某個形狀時,isDragging欄位被設定為true,selectedVisual欄位被設定為被單擊的視覺化物件,而clickOffset欄位記錄了使用者單擊點和正方形左上角之間的距離。下面是MouseLeftButtonDown事件處理程式中的相關程式碼: 

else if (cmdSelectMove.IsChecked == true)
            {
                DrawingVisual visual = drawingSurface.GetVisual(pointClicked);
                if (visual != null)
                {
                    // Calculate the top-left corner of the square.
                    // This is done by looking at the current bounds and
                    // removing half the border (pen thickness).
                    // An alternate solution would be to store the top-left
                    // point of every visual in a collection in the 
                    // DrawingCanvas, and provide this point when hit testing.
                    Point topLeftCorner = new Point(
                        visual.ContentBounds.TopLeft.X + drawingPen.Thickness / 2,
                        visual.ContentBounds.TopLeft.Y + drawingPen.Thickness / 2);
                    DrawSquare(visual, topLeftCorner, true);

                    clickOffset = topLeftCorner - pointClicked;
                    isDragging = true;

                    if (selectedVisual != null && selectedVisual != visual)
                    {
                        // The selection has changed. Clear the previous selection.
                        ClearSelection();
                    }
                    selectedVisual = visual;
                }

  除基本的記錄資訊外,上面的程式碼還呼叫DrawSquare()方法,使用新顏色重新渲染DrawingVisual物件。上面的程式碼還使用另一個自定義方法ClearSelection(),該方法重新繪製以前選中的正方形,使該正方形恢復其正常外觀: 

private void ClearSelection()
        {
            Point topLeftCorner = new Point(
                        selectedVisual.ContentBounds.TopLeft.X + drawingPen.Thickness / 2,
                        selectedVisual.ContentBounds.TopLeft.Y + drawingPen.Thickness / 2);
            DrawSquare(selectedVisual, topLeftCorner, false);
            selectedVisual = null;
        }

  接下來,當用戶拖動時需要實際移動正方形,並當使用者釋放滑鼠左鍵時結束拖動操作。這兩個任務是使用一些簡單的事件處理程式碼完成的: 

private void drawingSurface_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }
private void drawingSurface_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point pointDragged = e.GetPosition(drawingSurface) + clickOffset;
                DrawSquare(selectedVisual, pointDragged, true);
            }
        }

四、複雜的命中測試

  在上面的示例中,命中測試程式碼始終返回最上面的視覺化物件(如果單擊空白處,就返回null引用)。然而,VisualTreeHelper類提供了HitTest()方法的兩個過載版本,從而可以執行更加複雜的命中測試。使用這些方法,可以檢索位於特定點的所有視覺化物件,即使它們被其他元素隱藏在後面也同樣如此。還可找到位於給定幾何圖形中的所有視覺化物件。

  為了使用這個更高階的命中測試行為,需要建立回撥函式。之後,VisualTreeHelper類自上而下遍歷所有視覺化物件(與建立它們的順序相反)。每當發現匹配的物件時,就會呼叫回撥函式並傳遞相關細節。然後可以選擇停止查詢(如果已經查詢到足夠的層次),或繼續查詢知道遍歷完所有的視覺化物件為止。

  下面的程式碼通過為DrawingCanvas類新增GetVisuals()方法實現了該技術。GetVisuals()方法接收一個Geometry物件,該物件用於命中測試。GetVisuals()方法建立回撥函式委託、清空命中測試結果的集合,然後通過呼叫VisualTreeHelper.HitTest()方法啟動命中測試過程。當該過程結束時,該方法返回包含所有找到的視覺化物件的集合: 

private List<DrawingVisual> hits = new List<DrawingVisual>();
        public List<DrawingVisual> GetVisuals(Geometry region)
        {
            hits.Clear();
            GeometryHitTestParameters parameters = new GeometryHitTestParameters(region);
            HitTestResultCallback callback = new HitTestResultCallback(this.HitTestCallback);
            VisualTreeHelper.HitTest(this, null, callback, parameters);
            return hits;
        }

  回撥方法實現了命中測試行為。通常,HitTestResult物件只提供一個熟悉(VisualHit),但可以根據執行命中測試的型別,將它轉換成兩個派生型別中的任意一個。

  如果使用一個點進行命中測試,可將HitTestResult物件轉換為PointHitTestResult物件,該類提供了一個不起眼的PointHit熟悉,該屬性返回用於執行命中測試的原始點。但如果使用Geometry物件吉祥鳥命中測試,如本例那樣,可將HitTestResult物件轉換為GeometryHitTestResult物件,並訪問IntersectionDetail屬性。IntersectionDetail屬性告知幾何圖形是否完全封裝了視覺化物件(FullyInside),幾何圖形是否與視覺化元素只是相互重疊(Intersets),或者用於命中測試的集合圖形是否落在視覺化元素的內部(FullyContains)。在該例中,只有當可視化物件完全位於命中測試區域時,才會對命中數量計算。最後,在回撥函式的末尾,可返回兩個HitTestResultBehavior列舉值中的一個:返回continue表示繼續查詢命中,返回Stop則表示結束查詢過程。 

private HitTestResultBehavior HitTestCallback(HitTestResult result)
        {
            GeometryHitTestResult geometryResult = (GeometryHitTestResult)result;
            DrawingVisual visual = result.VisualHit as DrawingVisual;
            if (visual != null &&
                geometryResult.IntersectionDetail == IntersectionDetail.FullyInside)
            {
                hits.Add(visual);
            }
            return HitTestResultBehavior.Continue;
        }

  使用GetVisuals()方法,可建立如下圖所示的複雜選擇框效果。在此,使用者在一組矩形的周圍繪製了一個方框。應用程式接著報告該區域中矩形的數量。

 

 

   為了建立選擇框,視窗只需要為DrawingCanvas面板新增另一個DrawingVisual物件即可。在視窗中還作為成員欄位儲存了指向選擇框的引用,此外還有isMultiSelecting標記和selectionSquareTopLeft欄位,當繪製選擇框時,isMultiSelecting標記跟蹤正在進行的選擇操作,selectionSquareTopLeft欄位跟蹤當前選擇框的左上角:

// Variables for drawing the selection square.
        private bool isMultiSelecting = false;
        private Point selectionSquareTopLeft;

  為實現選擇框特性,需要為前面介紹的事件處理程式新增一些程式碼。當單擊滑鼠時,需要建立選擇框,將isMultiSelecting開關設定為true,並捕獲滑鼠。下面的MouseLeftButtonDown事件處理程式中的程式碼完成這項工作:

else if (cmdSelectMultiple.IsChecked == true)
            {

                selectionSquare = new DrawingVisual();

                drawingSurface.AddVisual(selectionSquare);

                selectionSquareTopLeft = pointClicked;
                isMultiSelecting = true;

                // Make sure we get the MouseLeftButtonUp event even if the user
                // moves off the Canvas. Otherwise, two selection squares could be drawn at once.
                drawingSurface.CaptureMouse();
            }

  現在,當移動滑鼠時,可根據當前選擇框是否處於啟用狀態。如果是啟用狀態,就繪製它。為此,需要在MouseMove事件處理程式中新增以下程式碼:

else if (isMultiSelecting)
            {
                Point pointDragged = e.GetPosition(drawingSurface);
                DrawSelectionSquare(selectionSquareTopLeft, pointDragged);
            }

  實際的繪圖操作在專門的DrawSelectionSquare()方法中進行,該方法與前面介紹的DrawSquare()方法有一些類似之處:

private Brush selectionSquareBrush = Brushes.Transparent;
        private Pen selectionSquarePen = new Pen(Brushes.Black, 2);

        private void DrawSelectionSquare(Point point1, Point point2)
        {
            selectionSquarePen.DashStyle = DashStyles.Dash;

            using (DrawingContext dc = selectionSquare.RenderOpen())
            {
                dc.DrawRectangle(selectionSquareBrush, selectionSquarePen,
                    new Rect(point1, point2));
            }
        }

  最後,當釋放滑鼠時,可執行命中測試,顯示訊息框,然後移除選擇框。為此,需要MouseLeftButtonUp事件處理程式中新增如下程式碼:

 if (isMultiSelecting)
            {
                // Display all the squares in this region.
                RectangleGeometry geometry = new RectangleGeometry(
                    new Rect(selectionSquareTopLeft, e.GetPosition(drawingSurface)));
                List<DrawingVisual> visualsInRegion =
                    drawingSurface.GetVisuals(geometry);
                MessageBox.Show(String.Format("You selected {0} square(s).", visualsInRegion.Count));

                isMultiSelecting = false;
                drawingSurface.DeleteVisual(selectionSquare);
                drawingSurface.ReleaseMouseCapture();
            }

本例項的完整程式碼如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Drawing
{
    public class DrawingCanvas:Panel
    {
        private List<Visual> visuals = new List<Visual>();

        protected override Visual GetVisualChild(int index)
        {
            return visuals[index];
        }
        protected override int VisualChildrenCount
        {
            get
            {
                return visuals.Count;
            }
        }

        public void AddVisual(Visual visual)
        {
            visuals.Add(visual);

            base.AddVisualChild(visual);
            base.AddLogicalChild(visual);
        }

        public void DeleteVisual(Visual visual)
        {
            visuals.Remove(visual);

            base.RemoveVisualChild(visual);
            base.RemoveLogicalChild(visual);
        }

        public DrawingVisual GetVisual(Point point)
        {
            HitTestResult hitResult = VisualTreeHelper.HitTest(this, point);
            return hitResult.VisualHit as DrawingVisual;
        }

        private List<DrawingVisual> hits = new List<DrawingVisual>();
        public List<DrawingVisual> GetVisuals(Geometry region)
        {
            hits.Clear();
            GeometryHitTestParameters parameters = new GeometryHitTestParameters(region);
            HitTestResultCallback callback = new HitTestResultCallback(this.HitTestCallback);
            VisualTreeHelper.HitTest(this, null, callback, parameters);
            return hits;
        }

        private HitTestResultBehavior HitTestCallback(HitTestResult result)
        {
            GeometryHitTestResult geometryResult = (GeometryHitTestResult)result;
            DrawingVisual visual = result.VisualHit as DrawingVisual;
            if (visual != null &&
                geometryResult.IntersectionDetail == IntersectionDetail.FullyInside)
            {
                hits.Add(visual);
            }
            return HitTestResultBehavior.Continue;
        }
    }
}
DrawingCanvas
<Window x:Class="Drawing.VisualLayer"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Drawing"
        Title="VisualLayer" Height="300" Width="394.737">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <ToolBarTray Orientation="Vertical">
            <ToolBar>
                <RadioButton Margin="0,3" Name="cmdSelectMove">
                    <StackPanel>
                        <Image Source="pointer.png" Width="35" Height="35"></Image>
                        <TextBlock>Select/Move</TextBlock>
                    </StackPanel>
                </RadioButton>
                <RadioButton Margin="0,3" IsChecked="True" Name="cmdAdd">
                    <StackPanel>
                        <Rectangle Width="30" Height="30" Stroke="SteelBlue" StrokeThickness="3" Fill="AliceBlue"></Rectangle>
                        <TextBlock>Add Square</TextBlock>
                    </StackPanel>
                </RadioButton>
                <RadioButton Margin="0,3" Name="cmdDelete">
                    <StackPanel>
                        <Path Stroke="SteelBlue" StrokeThickness="4" StrokeEndLineCap="Round" StrokeStartLineCap="Round"
                  Fill="Red" HorizontalAlignment="Center">
                            <Path.Data>
                                <GeometryGroup>
                                    <PathGeometry>
                                        <PathFigure StartPoint="0,0">
                                            <LineSegment Point="18,18"></LineSegment>
                                        </PathFigure>
                                        <PathFigure StartPoint="0,18">
                                            <LineSegment Point="18,0"></LineSegment>
                                        </PathFigure>
                                    </PathGeometry>
                                </GeometryGroup>
                            </Path.Data>
                        </Path>
                        <TextBlock>Delete Square</TextBlock>
                    </StackPanel>
                </RadioButton>
                <RadioButton Margin="0,3" Name="cmdSelectMultiple">
                    <StackPanel>
                        <Image Source="pointer.png" Width="35" Height="35"></Image>
                        <TextBlock>Select Multiple</TextBlock>
                    </StackPanel>
                </RadioButton>
            </ToolBar>
        </ToolBarTray>
        <Border Grid.Column="1" Margin="3" BorderThickness="3" BorderBrush="SteelBlue">
            <local:DrawingCanvas x:Name="drawingSurface" Background="White" ClipToBounds="True"
                             MouseLeftButtonDown="drawingSurface_MouseLeftButtonDown"
                MouseLeftButtonUp="drawingSurface_MouseLeftButtonUp"
                MouseMove="drawingSurface_MouseMove"></local:DrawingCanvas>
        </Border>
    </Grid>
</Window>
VisualLayer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Drawing
{
    /// <summary>
    /// VisualLayer.xaml 的互動邏輯
    /// </summary>
    public partial class VisualLayer : Window
    {
        public VisualLayer()
        {
            InitializeComponent();
            DrawingVisual v = new DrawingVisual();
            DrawSquare(v, new Point(10, 10), false);
        }

        // Variables for dragging shapes.
        private bool isDragging = false;
        private Vector clickOffset;
        private DrawingVisual selectedVisual;

        // Variables for drawing the selection square.
        private bool isMultiSelecting = false;
        private Point selectionSquareTopLeft;

        private void drawingSurface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Point pointClicked = e.GetPosition(drawingSurface);

            if (cmdAdd.IsChecked == true)
            {
                DrawingVisual visual = new DrawingVisual();
                DrawSquare(visual, pointClicked, false);
                drawingSurface.AddVisual(visual);
            }
            else if (cmdDelete.IsChecked == true)
            {
                DrawingVisual visual = drawingSurface.GetVisual(pointClicked);
                if (visual != null) drawingSurface.DeleteVisual(visual);
            }
            else if (cmdSelectMove.IsChecked == true)
            {
                DrawingVisual visual = drawingSurface.GetVisual(pointClicked);
                if (visual != null)
                {
                    // Calculate the top-left corner of the square.
                    // This is done by looking at the current bounds and
                    // removing half the border (pen thickness).
                    // An alternate solution would be to store the top-left
                    // point of every visual in a collection in the 
                    // DrawingCanvas, and provide this point when hit testing.
                    Point topLeftCorner = new Point(
                        visual.ContentBounds.TopLeft.X + drawingPen.Thickness / 2,
                        visual.ContentBounds.TopLeft.Y + drawingPen.Thickness / 2);
                    DrawSquare(visual, topLeftCorner, true);

                    clickOffset = topLeftCorner - pointClicked;
                    isDragging = true;

                    if (selectedVisual != null && selectedVisual != visual)
                    {
                        // The selection has changed. Clear the previous selection.
                        ClearSelection();
                    }
                    selectedVisual = visual;
                }
            }
            else if (cmdSelectMultiple.IsChecked == true)
            {

                selectionSquare = new DrawingVisual();

                drawingSurface.AddVisual(selectionSquare);

                selectionSquareTopLeft = pointClicked;
                isMultiSelecting = true;

                // Make sure we get the MouseLeftButtonUp event even if the user
                // moves off the Canvas. Otherwise, two selection squares could be drawn at once.
                drawingSurface.CaptureMouse();
            }
        }

        // Drawing constants.
        private Brush drawingBrush = Brushes.AliceBlue;
        private Brush selectedDrawingBrush = Brushes.LightGoldenrodYellow;
        private Pen drawingPen = new Pen(Brushes.SteelBlue, 3);
        private Size squareSize = new Size(30, 30);
        private DrawingVisual selectionSquare;

        // Rendering the square.
        private void DrawSquare(DrawingVisual visual, Point topLeftCorner, bool isSelected)
        {
            using (DrawingContext dc = visual.RenderOpen())
            {
                Brush brush = drawingBrush;
                if (isSelected) brush = selectedDrawingBrush;

                dc.DrawRectangle(brush, drawingPen,
                    new Rect(topLeftCorner, squareSize));
            }
        }

        private void drawingSurface_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;

            if (isMultiSelecting)
            {
                // Display all the squares in this region.
                RectangleGeometry geometry = new RectangleGeometry(
                    new Rect(selectionSquareTopLeft, e.GetPosition(drawingSurface)));
                List<DrawingVisual> visualsInRegion =
                    drawingSurface.GetVisuals(geometry);
                MessageBox.Show(String.Format("You selected {0} square(s).", visualsInRegion.Count));

                isMultiSelecting = false;
                drawingSurface.DeleteVisual(selectionSquare);
                drawingSurface.ReleaseMouseCapture();
            }
        }

        private void ClearSelection()
        {
            Point topLeftCorner = new Point(
                        selectedVisual.ContentBounds.TopLeft.X + drawingPen.Thickness / 2,
                        selectedVisual.ContentBounds.TopLeft.Y + drawingPen.Thickness / 2);
            DrawSquare(selectedVisual, topLeftCorner, false);
            selectedVisual = null;
        }

        private void drawingSurface_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point pointDragged = e.GetPosition(drawingSurface) + clickOffset;
                DrawSquare(selectedVisual, pointDragged, true);
            }
            else if (isMultiSelecting)
            {
                Point pointDragged = e.GetPosition(drawingSurface);
                DrawSelectionSquare(selectionSquareTopLeft, pointDragged);
            }
        }

        private Brush selectionSquareBrush = Brushes.Transparent;
        private Pen selectionSquarePen = new Pen(Brushes.Black, 2);

        private void DrawSelectionSquare(Point point1, Point point2)
        {
            selectionSquarePen.DashStyle = DashStyles.Dash;

            using (DrawingContext dc = selectionSquare.RenderOpen())
            {
                dc.DrawRectangle(selectionSquareBrush, selectionSquarePen,
                    new Rect(point1, point2));
            }
        }
    }
}
VisualLayer.xaml.cs

&n