天天看點

C#委托實作WPF主窗體向多個子窗體廣播傳遞消息

窗體之間傳遞消息并不罕見,實作方式各有不同,今天主要記錄下C#當中通過委托(Delegate)實作主窗體向多個子窗體發送消息的簡單示例。

一、原理分析

C#委托實作WPF主窗體向多個子窗體廣播傳遞消息

壹般來說,壹個應用程式是由若幹個窗體構成的,通過适當的互動邏輯在不同窗體之間建立起聯系。當主窗體不友善直接調用子窗體内部的方法時,可通過委托的方式來間接調用。隻需要子窗體定義壹個滿足主窗體聲明的委托要求的方法即可。然後在主窗體執行個體化從窗體,并将委托變量和從窗體方法關聯起來,再調用委托來完成!

二、代碼實作

1、主窗體

主窗體當中放置兩個按鈕為計數和重置,按鈕事件分别為ClickMe和ResetMe,在此隻附上C#代碼,XAML布局代碼略。

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.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DelegateMainFormToSubFormMessage
{
    //聲明委托
    public delegate void MessageShow(string Counter);
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //建立委托對象
        public MessageShow messageShow;
        private int counter = 0;
        public MainWindow()
        {
            InitializeComponent();
            //顯示子窗體
            SubFormA subFormA = new SubFormA();
            SubFormB subFormB = new SubFormB();
            SubFormC subFormC = new SubFormC();
            subFormA.Show();
            subFormB.Show();
            subFormC.Show();
            this.messageShow += subFormA.Receiver;
            this.messageShow += subFormB.Receiver;
            this.messageShow += subFormC.Receiver;
        }
        //計數按鈕事件
        private void ClickMe(object sender, RoutedEventArgs e)
        {
            this.counter++;
            this.messageShow.Invoke(counter.ToString());
        }
        //重置按鈕事件
        private void ResetMe(object sender, RoutedEventArgs e)
        {
            this.counter = 0;
            this.messageShow.Invoke("0");
        }
    }

}

           
2、從窗體

三個子窗體分别為SubFormA、SubFormB、SubFormC,對應的Label控件名稱分别為SubFormALabel、SubFormBLabel、SubFormCLabel,都 擁有和委托要求相比對的Receiver方法(無傳回值,方法要求傳入壹個string類型參數)如下:

//SubFormA
        public void Receiver(string Counter)
        {
            this.SubFormALabel.Content = Counter;
        }
           
//SubFormB
        public void Receiver(string Counter)
        {
            this.SubFormBLabel.Content = Counter;
        }
           
//SubFormC
        public void Receiver(string Counter)
        {
            this.SubFormCLabel.Content = Counter;
        }
           

主窗體構造函數當中執行個體化三個從窗體并顯示,點選“計數”按鈕,三個從窗體的Label控件接收從主窗體傳遞過來的值并同步顯示;主窗體點選“重置”按鈕的時候,将三個從窗體的Label控件的内容設定為字元串“0”。

三、效果預覽

C#委托實作WPF主窗體向多個子窗體廣播傳遞消息

在WPF當中,不同窗體其本質就是不同的類,隻不過不像WinForm那樣,WPF程式的每個窗體界面部分交由XAML标簽語言來完成,背景程式邏輯還是C#語言,最終将XAML代碼和C#代碼以“部分類”的方式合并為壹個類。本次代碼XAML部分隻是簡單的拖放按鈕和文本控件,沒有涉及複雜的布局樣式,故不再展示XAML代碼。C#代碼同樣隻是簡單幾行,高手可以略過,隻為初學C#的同行在漫長的學習過程中分享壹點知識!

繼續閱讀