天天看點

【WPF學習】第三十八章 行為

  樣式提供了重用一組屬性設定的實用方法。它們為幫助建構一緻的、組織良好的界面邁出了重要的第一步——但是它們也是有許多限制。

  問題是在典型的應用程式中,屬性設定僅是使用者界面基礎結構的一小部分。甚至最基本的程式通常也需要大量的使用者界面代碼,這些代碼與應用程式的功能無關。在許多程式中,用于使用者界面任務的代碼(如驅動動畫、實作平滑效果、維護使用者界面狀态,以及支援諸如拖放、縮放以及停靠等使用者界面特性)無論是在數量山還是複雜性上都超出了業務代碼。許多這類代碼是通用的,這意味着在建立的每個WPF對象中需要編寫相同的内容。所有這些工作幾乎都單調乏味的。

  為回應這一挑戰,Expression Blend創作者開發了稱為行為(behavior)的特征。其思想很簡單:建立封裝了一些通用使用者界面功能的行為。這一功能可以是基本功能(如啟動故事闆或導航到超連結),也可以是複雜功能(如處理多點觸摸互動,或建構使用實時實體引擎的碰撞模型)。一旦建構功能,就可将它們添加到任意應用程式的另一個控件中,具體方法是将該控件連結到适當的行為并設定行為的屬性。在Expression Blend中,隻通過拖放操作就可以使用行為。

一、擷取行為支援

  重用使用者界面的代碼通用塊得基礎結構不是WPF的一部分。反而,它被捆綁到Expression Blend。這是因為行為開始時作為Expression Blend的設計時特性引入的。但這并不意味着行為隻能用于Expression Blend。隻需要付出很少的努就可以在Visual Studio應用程式中的建立和使用行為。隻需要手動縮寫标記,而不是使用工具箱。

  為了獲得支援行為的程式集,有兩種選擇:

  •   可按照Expression Blend 3、Expression Blend 4 或Visual Studio 2012以上版本。所有這些版本都包含Visual Studio中的行為功能所需的程式集。
  •   可安裝Expression Blend SDK。

  無論是使用Expression Blend的哪個版本,都可以在檔案夾中看到所需的兩個相同的重要程式集:

  •   System.Windows.Interactivity.dll。這個程式集定義了支援行為的基本類。它是行為特征的基礎。
  •   Microsoft.Expression.Interactions.dll。這個程式集通過添加可選的以核心行為類為基礎的動作和觸發器類,增加了一些有用的擴充。

二、了解行為模型

  行為特性具有兩個版本:一個版本是旨在Silverlight添加行為支援,Silverlight是Microsoft的針對浏覽器的富用戶端插件;而另一個版本是針對WPF設計的。盡管這兩個版本提供了相同的特性,但行為特性和Silverlight領域更吻合,因為它彌補了更大的鴻溝。與WPF不同,Silverlight不支援觸發器,是以實作行為的程式集也實作觸發器更合理。然而,WPF支援觸發器,行為特性包含自己的觸發器系統,而觸發器系統與WPF模型不比對,這确實令人感到有些困惑。

  問題在于具有類似名稱的這兩個特性有部分重合但不完全相同。在WPF中,觸發器最重要的角色是建構靈活的樣式和控件模闆。在觸發器的幫助下,樣式和模闆變得更加智能;例如,當一些熟悉發生變化時可應用可視化效果。然而,Expression Blend中的觸發器系統具有不同的目的。通過使用可視化設計工具,允許為應用程式添加簡單功能。換句話說,WPF觸發器支援更加強大的樣式和控件模闆。而Expression Blend觸發器支援快速的不需要代碼的應用程式設計。

  那麼,對于使用WPF的普遍開發人員來說所有這些意味着什麼呢?下面是幾條指導原則:

  •   行為模型不是WPF的核心部分,是以行為不像樣式和模闆那樣确定。換句話說,可編寫不使用行為的WPF應用程式,但如果不使用樣式和模闆,就不能建立比“Hello World”示範更複雜的WPF應用程式。
  •   如果在Expression Blend上耗費大量時間,或希望為其他Expression Blend使用者開發元件,可能會對Expression Blend中的觸發器特性感興趣。盡管和WPF中的觸發器系統使用相同的名稱,但它們不能互相重疊,可以同時使用這兩者。
  •   如果不使用Expression Blend,可完全略過觸發器特性——但仍應分析Expression Blend提供的功能完整的行為類。這是因為行為比Expression Blend的觸發器更強大也更常用。最終,将準備查找那些提供了可在自己的應用程式中使用的整潔美觀行為的第三方元件。

三、建立行為

  行為旨在封裝一些UI功能,進而可以不比編寫代碼就能夠将其應用到元素上。從另一個角度看,每個行為都為元素提供了一個服務。該服務通常涉及監聽幾個不同的事件并執行幾個相關的操作。

  為更好地了解行為,最好自己建立一個行為。設想希望為任意元素提供使用滑鼠在Canvas面闆上拖動元素的功能。對于單個元素實作該功能的基本步驟是非常簡單的——代碼監聽滑鼠事件并修改設定相應Canvas坐标的附加屬性。但通過付出更多一點的努力,可将該代碼轉換為可重用的行為,該行為可為Canvas面闆上的所有元素提供拖動支援。

  在繼續之前,建立一個WPF類庫程式集。在該程式集中,添加System.Windows.Interactivity.dll程式集的引用。然後,建立一個繼承自Behavior基類的類。Behavior是通用類,該類使用一個類型參數。可使用該類型參數将行為限制到特定的元素,或使用UIElement或FrameworkElement将它們都包含進來。如下所示:

public class DragInCanvasBehavior : Behavior<UIElement>
    {  }      

  在任何行為中,第一步要覆寫OnAttached()和OnDetaching()方法。當調用OnAttached()方法時,可通過AssociatedObject屬性通路放置行為的元素,并可關聯事件處理程式。當調用OnDetaching()方法時,移除事件處理程式。

  下面是DragInCanvasBehavior類用于監視MouseLeftButtonDown、MouseMove以及MouseLeftButtonUp事件代碼:

protected override void OnAttached()
        {
            base.OnAttached();

            // Hook up event handlers.            
            this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseMove += AssociatedObject_MouseMove;
            this.AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            // Detach event handlers.
            this.AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
            this.AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;
        }      

  最後一步是在事件處理程式中運作适當的代碼。例如,當使用者單擊滑鼠左鍵時,DragInCanvasBehavior開始拖動操作、記錄元素左上角與滑鼠指針之間的偏移并捕獲滑鼠:

private Canvas canvas;
// Keep track of when the element is being dragged.
        private bool isDragging = false;

        // When the element is clicked, record the exact position
        // where the click is made.
        private Point mouseOffset;

        private void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Find the canvas.
            if (canvas == null) canvas = VisualTreeHelper.GetParent(this.AssociatedObject) as Canvas;

            // Dragging mode begins.
            isDragging = true;

            // Get the position of the click relative to the element
            // (so the top-left corner of the element is (0,0).
            mouseOffset = e.GetPosition(AssociatedObject);

            // Capture the mouse. This way you'll keep receiveing
            // the MouseMove event even if the user jerks the mouse
            // off the element.
            AssociatedObject.CaptureMouse();
        }              

  當元素處于拖動模式并移動滑鼠時,重新定位元素:

private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                // Get the position of the element relative to the Canvas.
                Point point = e.GetPosition(canvas);

                // Move the element.
                AssociatedObject.SetValue(Canvas.TopProperty, point.Y - mouseOffset.Y);
                AssociatedObject.SetValue(Canvas.LeftProperty, point.X - mouseOffset.X);
            }
        }      

  當釋放滑鼠鍵時,結束拖動:

private void AssociatedObject_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (isDragging)
            {
                AssociatedObject.ReleaseMouseCapture();
                isDragging = false;
            }
        }      

  DragInCanvasBehavior類的完整代碼如下所示:

【WPF學習】第三十八章 行為
【WPF學習】第三十八章 行為
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.Input;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace CustomBehaviorsLibrary
{
    public class DragInCanvasBehavior : Behavior<UIElement>
    {
        private Canvas canvas;

        protected override void OnAttached()
        {
            base.OnAttached();

            // Hook up event handlers.            
            this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseMove += AssociatedObject_MouseMove;
            this.AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            // Detach event handlers.
            this.AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
            this.AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;
        }

        // Keep track of when the element is being dragged.
        private bool isDragging = false;

        // When the element is clicked, record the exact position
        // where the click is made.
        private Point mouseOffset;

        private void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Find the canvas.
            if (canvas == null) canvas = VisualTreeHelper.GetParent(this.AssociatedObject) as Canvas;

            // Dragging mode begins.
            isDragging = true;

            // Get the position of the click relative to the element
            // (so the top-left corner of the element is (0,0).
            mouseOffset = e.GetPosition(AssociatedObject);

            // Capture the mouse. This way you'll keep receiveing
            // the MouseMove event even if the user jerks the mouse
            // off the element.
            AssociatedObject.CaptureMouse();
        }

        private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                // Get the position of the element relative to the Canvas.
                Point point = e.GetPosition(canvas);

                // Move the element.
                AssociatedObject.SetValue(Canvas.TopProperty, point.Y - mouseOffset.Y);
                AssociatedObject.SetValue(Canvas.LeftProperty, point.X - mouseOffset.X);
            }
        }

        private void AssociatedObject_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (isDragging)
            {
                AssociatedObject.ReleaseMouseCapture();
                isDragging = false;
            }
        }
    }
}      

DragInCanvasBehavior

四、使用行為

  為測試行為,建立一個新的WPF應用程式項目。然後添加對定義DragInCanvasBehavior類的類庫以及System.Windows.Interactivity.dll程式集得應用。接下來在XML中映射這兩個标記名稱。假定存儲DragInCanvasBehavior類的類庫名為CustomBehaviorsLibrary,所需的标記如下所示:

<Window x:Class="BehaviorTest.DragInCanvasTest"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:custom="clr-namespace:CustomBehaviorsLibrary;assembly=CustomBehaviorsLibrary"
        Title="DragInCanvasTest" Height="300" Width="300">      

  為使用該行為,隻需要使用Interaction.Behaviors附加屬性在Canvas面闆中添加任意元素。下面的标記建立一個具有三個圖形的Canvas面闆。兩個Ellipse元素使用了DragInCanvasBehavior,并能在Canvas面闆中拖動。Rectangle元素沒有使用DraginCanvasBehavior,是以無法移動。

<Canvas>
        <Rectangle Canvas.Left="10" Canvas.Top="10" Fill="Yellow" Width="40" Height="60"></Rectangle>
        <Ellipse Canvas.Left="10" Canvas.Top="70" Fill="Blue" Width="80" Height="60">
            <i:Interaction.Behaviors>
                <custom:DragInCanvasBehavior></custom:DragInCanvasBehavior>
            </i:Interaction.Behaviors>
        </Ellipse>
        <Ellipse Canvas.Left="80" Canvas.Top="70" Fill="OrangeRed" Width="40" Height="70">
            <i:Interaction.Behaviors>
                <custom:DragInCanvasBehavior></custom:DragInCanvasBehavior>
            </i:Interaction.Behaviors>
        </Ellipse>
    </Canvas>      

  下圖顯示了該例的運作效果。

【WPF學習】第三十八章 行為

  

DragInCanvasTest完整代碼:      
【WPF學習】第三十八章 行為
【WPF學習】第三十八章 行為
<Window x:Class="BehaviorTest.DragInCanvasTest"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:custom="clr-namespace:CustomBehaviorsLibrary;assembly=CustomBehaviorsLibrary"
        Title="DragInCanvasTest" Height="300" Width="300">
    <Canvas>
        <Rectangle Canvas.Left="10" Canvas.Top="10" Fill="Yellow" Width="40" Height="60"></Rectangle>
        <Ellipse Canvas.Left="10" Canvas.Top="70" Fill="Blue" Width="80" Height="60">
            <i:Interaction.Behaviors>
                <custom:DragInCanvasBehavior></custom:DragInCanvasBehavior>
            </i:Interaction.Behaviors>
        </Ellipse>
        <Ellipse Canvas.Left="80" Canvas.Top="70" Fill="OrangeRed" Width="40" Height="70">
            <i:Interaction.Behaviors>
                <custom:DragInCanvasBehavior></custom:DragInCanvasBehavior>
            </i:Interaction.Behaviors>
        </Ellipse>
    </Canvas>
</Window>      

DragInCanvasTest

  但這并非是全部内容。如果正在使用Expression Blend進行開發,行為甚至提供了更好的設計體驗——可以根本不用編寫任何标記。

作者:Peter Luo

出處:https://www.cnblogs.com/Peter-Luo/

本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,并保留此段聲明,否則保留追究法律責任的權利。

繼續閱讀