我有一个包含多个Threads
的wpf项目,我还有Usercontrol
progressbar
和TextBlock
来表示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
。提前谢谢!
答案 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());
}