建立自訂行為
Behavior 可以直接作用,不需要來自 Trigger 或類似 Trigger 之項目的任何外部通知。雖然需要符合某些條件,但不必由 Trigger 叫用行為。
簡單行為
撰寫不需任何外部輸入的 Behavior 相當簡單。下列程式碼範例顯示基準線 Behavior :
public class MyBehavior : Behavior<DependencyObject>
{
public MyBehavior()
{
}
protected override void OnAttached()
{
base.OnAttached();
// Insert code that you want to run when the Behavior is attached to an object.
}
protected override void OnDetaching()
{
base.OnDetaching();
}
}
延伸 Behavior 類別,並將它限制在要與行為產生關聯的類型。
如同使用 Triggers 的 OnAttaching 和 OnDetaching 方法,您也可以在 Behavior 與某個物件關聯或正從其目前關聯的物件解除關聯時,將任何想要執行的程式碼放在 Behaviors 的 OnAttached 和 OnDetaching 方法中。
含有命令的行為
讓使用者自訂行為功能的方式之一是公開 Commands ( ICommand 類型的任何屬性),每個命令都會對應至 Behavior 可以執行的動作。首先,請確認您的專案包含 Microsoft.Expression.Interactions 和 System.Windows.Interactivity DLL 的參照。接下來,建立新的 Class 檔案,並新增下列程式碼:
public class BehaviorWithCommand : Behavior<DependencyObject>
{
public BehaviorWithCommand()
{
this.MyCommand = new ActionCommand(this.MyFunction);
}
protected override void OnAttached()
{
base.OnAttached();
}
protected override void OnDetaching()
{
base.OnDetaching();
}
public ICommand MyCommand
{
get;
private set;
}
private void MyFunction()
{
// Code to execute when your Command is called
}
}
下圖提供 Commands 和 Behaviors 如何搭配運作以提供類似 Action 之功能的概觀:
如上圖所示, Behavior 會公開 Commands 。現有的 Triggers 和 Actions 樣式可用於叫用這些 Commands ,方法是將 Triggers 新增至 Behavior ,並使這些 Triggers 觸發一或多個 InvokeCommandActions 。 InvokeCommandAction 只做一件事情,就是呼叫在 Behavior 上公開的 Command 。