[Excalibur]ASP.NET MVVM - 兩個Extensions UserControl互動與相互傳值的方法

UserControl互動與相互傳值的方法

如果常在WebForm應用程式中切割一堆UserControl使用
難免會碰上互動傳值的問題,而且解法應該不少
普通情況只要頁面上有Register過ascx路徑都可以取得類別型態與Property/Event
然後也能利用FindControl和Interface來處理...等等
但若是兩個UserControl放置在千里之遙
甚至不在氣泡事件OnBubbleEvent能解決的樣版關係的情況下
可以試試以下設計的方法

public partial class UserControl1 : Extensions.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        this.SendMessage("Command", TextBox1.Text);
    }
}
public partial class UserControl2 : Extensions.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.MessageNotify += UserControl2_MessageNotify;
    }
    protected void UserControl2_MessageNotify(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "Command")
        {
            Label1.Text = e.CommandArgument.ToString();
        }
    }
}

SendMessage方法傳送的第一個參數即MessageNotify事件EventArgs的CommandName
第二個參數即事件EventArgs的CommandArgument
MessageNotify中的sender則是發送訊息的UserControl物件

 

這裡呼叫SendMessage會對Page內所有Extensions UserControl註冊的MessageNotify事件進行觸發
但是不會觸發發送訊息的UserControl自己本身註冊的MessageNotify事件
所以也能在MessageNotify事件時呼叫SendMessage傳送其他訊息出去

 

(MVVM 1.1.1.8版本以上加入)

後記:在更新版本中加入了Attribute的使用方法,示例中的UserControl2可改寫成這樣

public partial class UserControl2 : Extensions.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [MessageNotifyMethod]
    public void Command(string text)
    {
        Label1.Text = text;
    }
}

相當於直接標註方法為可讓其他控制項以SendMessage公開呼叫的意思
呼叫的Command為指定的方法名稱,Argument為參數