目录
一、前言
废话少说,快上代码C# 干货全解_qinze5857的博客-CSDN博客
二、实例
DegtThd.cs
namespace wpfConsoleApp
{
public class DegtThd
{
//在线程的cs文件中声明一个委托
public delegate void SetTextCallback(string text);
public SetTextCallback tbCbkFxn;
public void callDelegateFxn()
{
int thdCnt = 0;
while(true)
{
//event and call
tbCbkFxn(thdCnt.ToString());
Thread.Sleep(10);
thdCnt++;
if(thdCnt>=100)
{
tbCbkFxn("byebye");
break;
}
}
}
}
}
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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 wpfConsoleApp
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
delegate void GMdelegate(string s);//通用的委托
public DegtThd dt;
public MainWindow()
{
InitializeComponent();
if (dt == null)
dt = new DegtThd();
dt.tbCbkFxn += SetText;//委托绑定
}
private void btn_console_Click(object sender, RoutedEventArgs e)
{
//ConsoleManager.Show();
//Console.WriteLine("在wpf中显示控制台");
Thread oThread = new Thread(new ThreadStart(dt.callDelegateFxn));//changeTBText
oThread.Start();
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
this.tb_easy.Dispatcher.Invoke(new GMdelegate(delegate(string s)
{
this.tb_easy.Text = s;
}),text);
}
private void changeTBText()
{
int cnt =0;
while(true)
{
this.SetText("tbox" + cnt.ToString());
Thread.Sleep(100);
cnt++;
if(cnt>=100)
{
this.SetText("tbox end");
break;
}
}
}
}
}