工程集如下:
<Window x:Class="SubClassCallMainClass.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:SubClassCallMainClass" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Grid > <RichTextBox VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" TextChanged="LogTextChanged" Margin="0,0,0,79" > <FlowDocument> <Paragraph x:Name="myParagraph" /> </FlowDocument> </RichTextBox> <Button x:Name="myButton" Content="开始" Click="BtnClickWork" HorizontalAlignment="Left" Margin="400,380,0,0" VerticalAlignment="Top"/> <Button Content="显示" Click="BtnClickDis" HorizontalAlignment="Left" Margin="478,380,0,0" VerticalAlignment="Top"/> </Grid> </Grid> </Window>
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 SubClassCallMainClass { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public int num = 0; public MainWindow() { InitializeComponent(); myWriteLog(Brushes.Black, "主类调用自己的方法"); } #region 打印日志方法 public void myWriteLog(SolidColorBrush color, string str) { myParagraph.Dispatcher.Invoke(new Action(() => { Run run = new Run() { Text = str, Foreground = color }; myParagraph.Inlines.Add(run); myParagraph.Inlines.Add(new LineBreak());//换行(如果用 也能换行,但是要把内容拷贝到Word里面 换行符不能识别,推荐使用LineBreak()来换行) })); } #endregion private void LogTextChanged(object sender, TextChangedEventArgs e) { RichTextBox richTextBox = sender as RichTextBox; richTextBox.ScrollToEnd(); } private void BtnClickWork(object sender, RoutedEventArgs e) { Work myWork = new Work();//实例化子类Work myWork.DoWork(this);//this 就是MainWindow类的实例,通过参数传递给子类Work,这样Work类就可以访问MainWindow的属性和方法了 } private void BtnClickDis(object sender, RoutedEventArgs e) { myWriteLog(Brushes.Black, $"主类num{num}"); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Media; namespace SubClassCallMainClass { public class Work { public void DoWork(MainWindow mainWindow) { var order = Task.Run(() => { for (; ; ) { mainWindow.num++;//更改MainWindow.xaml.cs主类的属性 Thread.Sleep(1000); mainWindow.myWriteLog(Brushes.Red, $"子类调用主类的方法,并且更改主类属性num:{mainWindow.num}");//访问MainWindow.xaml.cs主类的方法 } }); } } }
效果如下:
把MainWindow.xaml.cs中的按键事件处理内容放到Work类中去处理,当工程比较大的时候,这样便于工程管理,源码下载地址:https://github.com/lizhiqiang0204/SubClassCallMainClass