WCF中使用控件的委托,线程中的UI委托

 

UI界面:

<Window x:Class="InheritDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <StackPanel>
            <Label MouseEnter="Label_MouseEnter" MouseLeave="Label_MouseLeave">test1</Label>
        </StackPanel>
    </Grid>
</Window>

后端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Threading;

namespace InheritDemo
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        private Thread myThread = null;//定义线程
        private delegate void MyDelegate(Object para);//定义委托
        public Window1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 鼠标移入启动线程(继续挂起线程)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Label_MouseEnter(object sender, MouseEventArgs e)
        {
            if (myThread == null)//启动线程
            {
                myThread = new Thread(ThreadMethod);
                myThread.IsBackground = true;//后台线程
                myThread.Start(sender);
            }
            else { myThread.Resume(); }//继续挂起线程
        }
        /// <summary>
        /// 鼠标移出挂起线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Label_MouseLeave(object sender, MouseEventArgs e)
        {
            if (myThread != null) { myThread.Suspend(); }//挂起线程
        }
        /// <summary>
        /// 线程事件调用委托
        /// </summary>
        /// <param name="para"></param>
        private void ThreadMethod(object para)
        {
            MyDelegate myDelegate = new MyDelegate(DelegateMethod);
            while (true)
            {
                this.Dispatcher.BeginInvoke(myDelegate, para);//调用委托
                Thread.Sleep(1000);//休眠1s
            }
        }
        /// <summary>
        /// 委托事件获取当前时间
        /// </summary>
        /// <param name="para"></param>
        private void DelegateMethod(object para)
        {
            Label lbl = (Label)para;
            lbl.Content = DateTime.Now.ToString();
        }
        
    }
}

 

posted @ 2015-05-21 13:11  nieweiking  阅读(394)  评论(0编辑  收藏  举报