首页 > 代码库 > C#通过事件跨类调用WPF主窗口中的控件

C#通过事件跨类调用WPF主窗口中的控件

xaml.cs文件:

 1 using System; 2 using System.Timers; 3 using System.Windows; 4 using System.Windows.Forms; 5 namespace ControlUsed 6 { 7      8     public partial class MainWindow 9     {10 11         public MainWindow()12         {13               Monitor.PartEvent += OnStep;//将该类中的函数注册到Monitor静态类的PartEvent事件中。14         }15         public  void OnStep(Object sender,MessageArgs message)16         {17           18             Application.Current.Dispatcher.Invoke(new Action(() =>19                 {20                     MyTextBlock.Text = message.Txtmessage;//设置对应xaml中控件的属性21                 }));22         }23      }24 }

MessageArgs类:

 1 public  class MessageArgs:EventArgs 2     { 3        public MessageArgs(string message) 4        { 5            this.TxtMessage = message; 6        } 7  8        public string TxtMessage { get; set; } 9        10     }

Monitor静态类:

 1  public static class Monitor 2     { 3       public static event  EventHandler<MessageArgs> PartEvent;//定义在Monitor中的一个事件,参数是MessageArgs对象 4  5        6       public static void InFunction(string message) 7        { 8            var messageArg = new MessageArgs 9                {10                    TxtMessage=message11                };12            if (PartEvent != null)//如果mainwindow构造函数中给PartEvent注册了函数就不为null13            {14                PartEvent(new object(), messageArg);//触发事件,执行所有注册过的函数15            }16        }17 18     public static bool MonitorCenter()19        {20          InFunction("change");//在外部类中修改TextBlock的Text21        }22 }

 

C#通过事件跨类调用WPF主窗口中的控件