建立自訂觸發程序和動作

TriggersActions 構成因果關係模型。 Trigger 會對原因做出反應,並叫用一或多個 Actions

建立觸發程序

Trigger 是聆聽特定條件 (例如事件觸發或將屬性設為特定的值),並叫用一或多個關聯 Actions 作為回應的物件。 Triggers 範圍從引發滑鼠或鍵盤事件時觸發 ActionEventTrigger ,到兩個物件相衝突時觸發 ActionCollisionTriggerTriggers 是可延伸的,因此您可以充分發揮創意,建立自訂的觸發程序。 Trigger 必須包含某些基本語法,才能在執行階段由 Behaviors 所辨識。

下列程式碼範例顯示基準線 Trigger

public class Trigger1 : TriggerBase<DependencyObject>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        // Insert code that you want to run when the Trigger is attached to an object.
    }

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

        // Insert code that you want to run when the Trigger is removed from an object.
    }

    //
    // To invoke any associated Actions when this Trigger gets called, use
    // this.InvokeActions(o), where o is an object that you can pass in as a parameter.
    //
}

在上述程式碼範例中,類別是從 TriggerBase 所延伸,而 TriggerBase 是在 System.Windows.Interactivity.dll 中所提供的類型。一旦從 TriggerBase 類別延伸類別後,便可以覆寫 OnAttachedOnDetaching 方法,如程式碼範例所示。

就在 Trigger 從其 AssociatedObject 解除關聯之前會呼叫 OnDetaching 。這表示物件仍可從 Trigger 的範圍使用,讓您的程式碼繼續作用於該物件,直到 OnDetaching 結束為止 (例如,在該物件上取消連接事件處理常式)。

Trigger 最重要的動作就是實際使它觸發。若要使 Trigger 觸發,必須呼叫 InvokeActions 方法。當呼叫 InvokeActions 時,會通知任何與此 Trigger 關聯的 Actions 發生作用。

建立動作

Trigger 是只能「聆聽」 ** 某些動作發生的物件。 Action 是只能「執行」 ** 某些動作的物件。

下列程式碼範例顯示基準線 Action

public class MyAction : TriggerAction<DependencyObject>
{
    public MyAction()
    {
        // Insert code required for object creation below this point.
    }

    protected override void Invoke(object o)
    {
        // Insert code that defines what the Action will do when it is triggered or invoked.
    }
}

Invoke 方法會由 Trigger 所呼叫,因此,請確認可以在 Invoke 方法中,以某種形式存取任何希望 Action 執行的程式碼。下列程式碼範例顯示叫用方法時會顯示 MessageBoxAction

public class ShowMessageBoxAction : TriggerAction<DependencyObject>
{
    public string Message
    {
        get { return (string)GetValue(MessageProperty); }
        set { SetValue(MessageProperty, value); }
    }

    public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(string), typeof(ShowMessageBoxAction), new PropertyMetadata(""));

    public ShowMessageBoxAction()
    {
        // Insert code required for object creation below this point.
    }

    protected override void Invoke(object o)
    {
        MessageBox.Show(Message);
    }
}

上述程式碼範例中的 Action ,比先前所示的簡單 Action 更複雜,但是仍存在使其成為 Action 的通用特性。 ShowMessageBoxAction 是從 TriggerAction 延伸,並覆寫 Invoke 方法。

目標元素

根據預設, Action 只能存取 AssociatedObject 屬性,也就是其所附加到的元素,不過您可以變更 Action 會影響什麼。若要使 Action 以其他元素為目標,請從 TargetedTriggerAction (而非 TriggerAction ) 延伸代表 Action 的類別:

public class MyAction : TargetedTriggerAction<DependencyObject>
{
    // See TriggerAction in the preceding code sample...
}

TargetedTriggerAction 延伸類別後,便可使用 TargetNameTarget 屬性取得目標元素的存取權。 AssociatedObject 永遠會指向目前與 Action 關聯的元素,因此,請避免交替使用 AssociatedObjectTargetNameTarget 屬性。

另請參閱

概念

建立自訂行為