wpf 登录时显示状态动态图

下面的示例演示了如何在登录过程时,界面上显示状态图标,登录完成后隐藏图标:

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

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Thread th1 = new Thread(Method1);            
            th1.Start();

            // show progressbar
            progressBar.Visibility = Visibility.Visible;
        }

        void Method1()
        {
            MessageBox.Show("starting");  

            // process your work...
            Thread.Sleep(5000);

            MessageBox.Show("ending");

            // hide progressbar
            this.Dispatcher.BeginInvoke(new Action(() => { progressBar.Visibility = Visibility.Collapsed; }));
        }
    }
<Window x:Class="WpfApp1.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:WpfApp1"
        xmlns:gif="http://wpfanimatedgif.codeplex.com"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    <Grid>
        <Image x:Name="progressBar" Height="50" Width="50" Visibility="Collapsed" gif:ImageBehavior.RepeatBehavior="Forever" gif:ImageBehavior.AnimatedSource="/progress.gif" />
    </Grid>
</Window>

In WPF, a DispatcherObject can only be accessed by the Dispatcher it is associated with. For example, a background thread cannot update the contents of a Button that is associated with the Dispatcher on the UI thread. In order for the background thread to access the Content property of the Button, the background thread must delegate the work to the Dispatcher associated with the UI thread. This is accomplished by using either Invoke or BeginInvokeInvoke is synchronous and BeginInvoke is asynchronous. The operation is added to the queue of the Dispatcher at the specified DispatcherPriority.

If BeginInvoke is called on a Dispatcher that has shut down, the status property of the returned DispatcherOperation is set to Aborted.

All of the methods on Dispatcher, with the exception of DisableProcessing, are free-threaded.

Objects that derive from DispatcherObject have thread affinity.

相关资源:https://docs.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcher?view=netframework-4.8

原文地址:https://www.cnblogs.com/hellowzl/p/11229812.html