WPF 线程更新UI界面

在线程中无法直接操作UI元素,可以通过线程的Dispatch.Invoke方法来更新UI界面。

XAML界面

<Window
        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:WpfApplication1"
        xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid" x:Class="WpfApplication1.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <DataGrid x:Name="dataGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
        <Button Content="Start" Name="btnTest" Click="btnTest_Click"></Button>
        <TextBlock Name="txtBlock" Text="ABC"></TextBlock>
    </StackPanel>
</Window>

线程操作代码

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(ThreadDo);
            th.Start();
        }

        private void ThreadDo()
        {
            Dispatcher.Invoke(() =>
            {
                txtBlock.Text = "xyz";
                btnTest.Content = "Started";
            });

            Thread.Sleep(5 * 1000);
            
            Dispatcher.Invoke(() =>
            {
                txtBlock.Text = "abc";
                btnTest.Content = "Stoped";
            });
        }
    }
展开阅读全文

没有更多推荐了,返回首页