如何动态更新我的UI
本文关键字:更新 我的 UI 动态 何动态 | 更新日期: 2023-09-27 17:53:11
我已经看了几个有关动态ui的问题,但我仍然不明白我错过了什么。此外,我已经学习了如何使用任务的教程,但我的理解仍然有限。以下是我想要实现的:
我的应用程序正在后台做一些工作,但我希望我的UI是响应。我尝试了以下方法(参见代码),但是UI直到调用分派器才开始更新。我希望UI状态为:
- 创建…——一旦CreatePivotTableButton被点击
- 建立连接…——在调用提供者之前。li>连接成功或连接失败取决于结果
-
。
<!-- language: lang-cs --> private void CreatePivotTableButton(object sender, RoutedEventArgs e) { this.StatusToBeDisplayed.Content = "Creating..."; this.DescriptionLabel.IsEnabled = false; this.TextBlockBorder.IsEnabled = true; List<CombinedData> items = (List<CombinedData>)CustomerComboBox.ItemsSource; List<int> selectedItems = new List<int>(); foreach (CombinedData item in items) { if (item.IsSelected) { selectedItems.Add(item.ReferenceId); } } PCTProvider provider = new PCTProvider(); ExportToExcel export = new ExportToExcel(); ExcelAutomation excelAutomation = new ExcelAutomation(); this.ResultTextBlock.Text = "Establishing Connection"; DataTable generateReportDataTable = provider.GetReportData(selectedItems); Excel.Workbook workbook = export.ExportDataTableToExcel(generateReportDataTable); Task updateTask = Task.Factory.StartNew(() => { Dispatcher.Invoke(new Action(() => excelAutomation.CreatePivotTable(workbook))); }).ContinueWith(result => { Dispatcher.Invoke(new Action(() => this.StatusToBeDisplayed.Content = "Done!")); Dispatcher.Invoke(new Action(() => OriginalStatus())); }, TaskScheduler.FromCurrentSynchronizationContext()); }
我认为你不需要ContinueWith
和/或可能的TaskScheduler
通过在Task中完成工作,您允许UI线程响应消息泵。您可能需要将CreatePivotTableButton
的更多工作移到Task中。
试试这个:
private void CreatePivotTableButton(object sender, RoutedEventArgs e)
{
this.StatusToBeDisplayed.Content = "Creating...";
this.DescriptionLabel.IsEnabled = false;
this.TextBlockBorder.IsEnabled = true;
// move the rest of the code into your Task to perform the work off the UI thread
Task updateTask = Task.Factory.StartNew(() =>
{
List<CombinedData> items = (List<CombinedData>)CustomerComboBox.ItemsSource;
List<int> selectedItems = new List<int>();
foreach (CombinedData item in items)
{
if (item.IsSelected)
{
selectedItems.Add(item.ReferenceId);
}
}
PCTProvider provider = new PCTProvider();
ExportToExcel export = new ExportToExcel();
ExcelAutomation excelAutomation = new ExcelAutomation();
Dispatcher.Invoke(new Action(() => this.ResultTextBlock.Text = "Establishing Connection"));
DataTable generateReportDataTable = provider.GetReportData(selectedItems);
Excel.Workbook workbook = export.ExportDataTableToExcel(generateReportDataTable);
excelAutomation.CreatePivotTable(workbook);
Dispatcher.Invoke(new Action(() => this.StatusToBeDisplayed.Content = "Done!"));
Dispatcher.Invoke(new Action(() => OriginalStatus()));
});
}