C# 利用介面在窗體間傳遞訊息(很基礎很實用)
介面是一組包含了函式型方法的資料結構。通過這組資料結構,客戶程式碼可以呼叫元件物件的功能。
我們在實際開發中,經常要用到在窗體間傳遞資料。很多情況下,我們用委託把資料從子窗體傳遞到主窗體,這個例子我們來看下如何利用介面把資料從主窗體廣播到所有子窗體。
新建一個工程,這裡我用WPF舉例,在WinForm內的實現是完全一樣的。
我們看到工程的主窗體是 MainWindow.xaml
首先我們定義一個介面:
public interface IMessage
{
void Broadcast(string strMsg);
}
裡面有個方法 Broadcast(string strMsg);
接下來我們在工程內新增三個子窗體 WindowA.xaml,WindowB.xaml,WindowC.xaml
每個子窗體都放上一個 TextBlock, 預設名稱:textBlock1
在每個子窗體都繼承我們剛定義的介面,並實現這個介面:
public partial class WindowA : Window, IMessage
{
public WindowA()
{
InitializeComponent();
}
#region IMessage 成員
public void Broadcast
{
this.textBlock1.Text = strMsg;
}
#endregion
}
public partial class WindowB : Window, IMessage
{
public WindowB()
{
InitializeComponent();
}
#region IMessage 成員
public void Broadcast(string strMsg)
{
this.textBlock1.Text = strMsg;
}
#endregion
}
public partial class WindowC: Window, IMessage
{
public WindowC()
{
InitializeComponent();
}
#region IMessage 成員
public void Broadcast(string strMsg)
{
this.textBlock1.Text = strMsg;
}
#endregion
}
在Visual Studio裡有個小技巧,雙擊IMessage,就會出現一個實現介面的選項,點選實現介面,Visual Studio 就會自動幫你實現這個介面的所有內容程式碼。
現在我們看主窗體程式碼如何呼叫這個介面:
在主窗體新增一個按鈕,
private List<IMessage> bMsg = new List<IMessage>();//定義一個介面物件集合來儲存訊息接受者的引用
WindowA a;
WindowB b;
WindowC c;
public MainWindow()
{
InitializeComponent();
a = new WindowA();
a.Show();
b = new WindowB();
b.Show();
c = new WindowC();
c.Show();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
bMsg.Add(a);//引用WindowA
bMsg.Add(b);//引用WindowB
bMsg.Add(c);//引用WindowC
foreach (var item in bMsg)
{
item.Broadcast("hi");
}
}
}
這樣,當我們點選主窗體的按鈕,字串"hi"就會同時出現在3個子窗體的TextBlock上面。
完整程式碼下載