WPF1: Set and Get value for a control in a form which run in another thread

In WinForm, when we trying to set a value for Text property of a TextBox control that run in another thread, we can use code like this:

int totalFileNumbers = ReturnTotalFiles() ;

delegate_SetBarMaximum del_SetMax = new delegate_SetBarMaximum ( SetProgressBar_Maximum );

Invoke ( del_SetMax , new Object [] { totalFileNumbers });

but we will found that the Invoke will not work in WPF. I read an article in the net and found that in WPF we should use tb_Time.Dispatcher.Invoke:

Sample:

XAML:

<Window x:Class="Sample_InvokeInWPF.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">
    <Grid ShowGridLines="False" Height="300" Width="480" >
        <Grid.RowDefinitions>
            <RowDefinition x:Name="row1" Height="50"/>
            <RowDefinition x:Name="row2" Height="50"/>
            <RowDefinition x:Name="row3" Height="50"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition x:Name="col1" Width="200"/>
            <ColumnDefinition x:Name="col2"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Region" Grid.Row="2" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontFamily="Tahoma" FontSize="16" />
        <TextBlock Text="Current Time" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontFamily="Tahoma" FontSize="16"/>
        <ComboBox x:Name="cb_TimeToShow" Grid.Row="2" Grid.Column="1" FontFamily="Tahoma" FontSize="16" Text="GMT"  >
            <ComboBoxItem Content="UTC" FontFamily="Tahoma" FontSize="16" HorizontalAlignment="Right" />
            <ComboBoxItem Content="GMT" FontFamily="Tahoma" FontSize="16" HorizontalAlignment="Right"/>
        </ComboBox>
       
        <TextBox x:Name="tb_Time" Grid.Row="1" Grid.Column="1" BorderThickness="10">
            <TextBox.BorderBrush >
                <LinearGradientBrush >
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="#FF30EB95" Offset="1"/>
                </LinearGradientBrush>
            </TextBox.BorderBrush>
        </TextBox>
        
        <Button x:Name="bt_StartNewThread" Content="Start Process of Displaying Time" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" FontFamily="Tahoma" FontSize="16" Click="bt_StartNewThread_Click" />
    </Grid>
</Window>

CS Code:

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;

namespace Sample_InvokeInWPF
{
    delegate void delegate_ShowTime();
    delegate void delegate_RunAnotherThread();
    /// <summary>
    
/// Interaction logic for MainWindow.xaml
    
/// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        private void bt_StartNewThread_Click(object sender, RoutedEventArgs e)
        {
            delegate_RunAnotherThread del_newThread = new delegate_RunAnotherThread(RunNewThread);
            del_newThread.BeginInvoke(new AsyncCallback(return_Result), del_newThread);
        }

        void return_Result(IAsyncResult ar)
        {
            delegate_RunAnotherThread del_newThread = (delegate_RunAnotherThread)ar.AsyncState;
            del_newThread.EndInvoke(ar);
        }

        void RunNewThread()
        {
            //This is the Current Thread that is running
            while (true)
            {
                //Get cb_TimeToShow Text value
                string region = string.Empty;
                cb_TimeToShow.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                {
                    region = cb_TimeToShow.Text.Trim();
                }));
                if (region == string.Empty)
                {
                    MessageBox.Show("Select one Region in Comobox");
                    return;
                }

                string StrTime = String.Empty;
                if (region == "GMT")
                    StrTime = System.DateTime.Now.Hour.ToString() + " H " + System.DateTime.Now.Minute.ToString() + " Min " + System.DateTime.Now.Second.ToString() + " Second ";
                else if (region == "UTC")
                    StrTime = System.DateTime.UtcNow.Hour.ToString() + " H " + System.DateTime.UtcNow.Minute.ToString() + " Min " + System.DateTime.UtcNow.Second.ToString() + " Second ";
                //Set tb_Time Text value
                tb_Time.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
                {
                    tb_Time.Text = StrTime;
                }));
            }
        }
    }
}
原文地址:https://www.cnblogs.com/qixue/p/2267849.html