zoukankan      html  css  js  c++  java
  • C# WPF 使用委托修改UI控件

        近段时间在自学WPF,是一个完全不懂WPF的菜鸟,对于在线程中修改UI控件使用委托做一个记录,给自已以后查询也给需要的参考:

    界面只放一个RichTextBox,在窗体启动时开起两个线程,调用两个函数,每隔1秒写一次当前时间

    一 界面XAML如下:

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
        <Grid>
            <ScrollViewer>
                <RichTextBox HorizontalAlignment="Stretch" Margin="12" Name="richTextBox1" VerticalAlignment="Stretch" />
            </ScrollViewer>
        </Grid>
    </Window>

    二 在界面启动时开启两个线程:

     1         private void Window_Loaded(object sender, RoutedEventArgs e)
     2         {
     3             //创建线程1
     4             Thread t1 = new Thread(new ThreadStart(T1));
     5             t1.Start();
     6 
     7             //创建线程2
     8             Thread t2 = new Thread(new ThreadStart(T2));
     9             t2.Start();
    10         }

    三 线程调用函数:

            /// <summary>
            /// 线程1调用函数
            /// add by 
            /// </summary>
            private void T1()
            {
                while (true)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    ShowMsg(string.Format("T1 {0}", System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:fff")));
                }
            }
            /// <summary>
            /// 线程2调用函数
            /// add by 
            /// </summary>
            private void T2()
            {
                while (true)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    ShowMsg(string.Format("T2 {0}", System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:fff")));
                }
            }

    三 写前端函数:

            private void ShowMsg(string sMsg)
            {
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate() {
                    richTextBox1.AppendText(string.Format("{0} 
    ",sMsg));
                });
            }
  • 相关阅读:
    一致性哈希算法
    Discourse 的标签(Tag)只能是小写的原因
    JIRA 链接 bitbucket 提示错误 Invalid OAuth credentials
    JIRA 如何连接到云平台的 bitbucket
    Apache Druid 能够支持即席查询
    如何在 Discourse 中配置使用 GitHub 登录和创建用户
    Apache Druid 是什么
    Xshell 如何导入 PuTTYgen 生成的 key
    windows下配置Nginx支持php
    laravel连接数据库提示mysql_connect() :Connection refused...
  • 原文地址:https://www.cnblogs.com/guojingmail2009/p/6426264.html
Copyright © 2011-2022 走看看