C# WPF线程操作

2020-08-19 11:34:10 浏览数 (2)

界面显示:

xaml:

代码语言:javascript复制
<Window x:Class="WpfApp3.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:WpfApp3"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Label Content="Label" Name="lblShow" HorizontalAlignment="Left" Margin="175,165,0,0" VerticalAlignment="Top"/>
        <Button Content="Button" Name="btnCtrl" Click="BtnCtrl_Click" HorizontalAlignment="Left" Margin="340,165,0,0" VerticalAlignment="Top" Width="75"/>

    </Grid>
</Window>

c#代码:

代码语言:javascript复制
using System.Threading;
using System.Windows;

namespace WpfApp3
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            th = new Thread(labShowThread);
        }

        private void labShowThread()
        {
            Dispatcher.Invoke(() =>
            {
                lblShow.Content = "在线程中修改了标签值";
            });
            
        }

        Thread th;
        private void BtnCtrl_Click(object sender, RoutedEventArgs e)
        {
            th.Start();
        }
    }
}

0 人点赞