窗口中有一个TreeView。我想在一个事件中从ItemsSource加载TreeViewItems,同时显示ProgressRing(MahApps.Metro.Controls)。
但是ProgressRing始终卡住。
我使用multithread&Dispatcher进程ItemsSource加载,也无法正常工作。
XAML:
...
<Button Name="startButton" Content="Start" Click="Start"/>
<controls:ProgressRing x:Name="p1" IsActive="False"></controls:ProgressRing>
<TreeView x:Name="treeView1"></TreeView>
...
CS:
private void Start(object sender, EventArgs e)
{
TreeViewItem root = new TreeViewItem() { Header = "Root", IsExpanded = true };
treeView1.Items.Add(root);
p1.IsActive = true;
Thread thread = new Thread(() =>
{
// Main work
InitTree(root, "D:\\");
startButton.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
(ThreadStart)delegate() {
p1.IsActive = false;
});
});
thread.Start();
}
private void InitTree(TreeViewItem item, string dir)
{
string[] dirs = Directory.GetDirectories(dir);
foreach (string subdir in dirs)
{
startButton.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle,
(ThreadStart)delegate()
{
TreeViewItem subItem = new TreeViewItem() { Header = subdir, IsExpanded= true };
item.Items.Add(subItem);
InitTree(subItem, subdir);
});
}
}
我已阅读并尝试的内容:
http://msdn.microsoft.com/en-us/library/ms741870(v=vs.110).aspx
专业的WPF编程,第31章。多线程
最佳答案
改变
foreach (string subdir in dirs)
{
startButton.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle,
(ThreadStart)delegate()
{
TreeViewItem subItem = new TreeViewItem() { Header = subdir, IsExpanded= true };
item.Items.Add(subItem);
InitTree(subItem, subdir);
});
}
到
foreach (string subdir in dirs)
{
TreeViewItem subItem = new TreeViewItem() { Header = subdir, IsExpanded= true };
startButton.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle,
(ThreadStart)delegate()
{
item.Items.Add(subItem);
});
InitTree(subItem, subdir);
}
会更好。
关于c# - 在WPF中更新大量UI时,ProgressRing卡住了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22394931/