C# 委托——轻松控制控件

目录

一、前言

二、实例


一、前言

废话少说,快上代码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;
                }
            }
        }

    }

}

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值