如何在WPF的线程中显示usercontrol?

时间:2017-08-17 01:34:00

标签: c# wpf multithreading user-controls

我有一个包含多个Threads的wpf项目,我还有Usercontrol progressbarTextBlock来表示Thread的进度。我的代码如下:

XAML:

<Button Command="{Binding Start}" /> //This button start the thread

视图模型:

private ICommand _start;
public ICommand Start
{
    get
    {
        if(_start == null)
        {
            _start = new RelayCommand(
            param => Start_Thread());
        }

        return _start;
    }
}

private void Start_Thread()
{
      ...//Some irrelevant juedgement codes here
      Thread t = new Thread(new ThreadStart(StartSample));
      t.Start();
}

StartSample帖子中,我想弹出一个Usercontrol来表示当前的进度。

Usercontrol XAML:

<UserControl 
     <TextBlock Text="{Binding Info, Source={StaticResource Resources}}" />
     <mui:ModernProgressRing Style="{StaticResource RotatingPlaneProgressRingStyle}" IsActive="True" />
</UserControl>

那么我应该在主线程运行时弹出UserControl。提前谢谢!

1 个答案:

答案 0 :(得分:0)

之前显示一个新窗口,其中包含的UI线程中的UserControl,然后在后台线程上启动长时间运行操作,然后在操作完成后关闭窗口。

推荐和最简单的方法是使用Task Parallel Library (TPL)

private void Start_Thread()
{
    Window win = new Window();
    win.Content = new YourUserControl();
    win.Show();

    Task.Factory.StartNew(() =>
    {
        Sample_Thread();
    }).ContinueWith(task =>
    {
        //this code runs back on the UI thread once the task has finished
        win.Close();
    }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}