【发布时间】:2017-11-15 23:15:23
【问题描述】:
我正在学习 WPF/C# 并尝试开发一个在数据网格中列出文件名的小型应用程序(Windows 10,.Net frame 4.5) 到目前为止代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.IO;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for ProcessFiles.xaml
/// </summary>
public partial class ProcessFiles : Window
{
List<FileInfo> myFileList = new List<FileInfo>();
public ProcessFiles()
{
InitializeComponent();
dGrid.AutoGenerateColumns = true;
dGrid.UpdateLayout();
}
private void pButton_Click(object sender, RoutedEventArgs e)
{
try
{
Task.Factory.StartNew(() => ListMyFiles(myFileList));
}
catch (Exception ex)
{
MessageBox.Show("Error " +ex.Message);
}
finally
{
MessageBox.Show("Done.");
}
dGrid.ItemsSource = myFileList;
}
private void ListMyFiles(List<FileInfo> mylist)
{
//throw new NotImplementedException();
foreach (FileInfo f in new DirectoryInfo(@"D:\Dummy2").GetFiles("*.*", SearchOption.TopDirectoryOnly))
{
// var currentFile = f;
System.Threading.Thread.Sleep(10);
Dispatcher.BeginInvoke(new Action(() =>
{
this.ReadyItem.Content = "Updating..." + f.FullName;
mylist.Add(f);
}), DispatcherPriority.Background);
}
}
}
}
Dispatcher 任务完成后,我面临着自动刷新数据网格的两难境地。如果我没有在按钮单击事件中的某处使用 MessageBox.Show() 激活 GUI 线程,则 GridView 不会显示任何数据,但是,最大化主窗口、添加 MessageBox 显示等开始显示填充的列。
我一定错过了什么?
【问题讨论】:
-
您是否正在实施 INotifyPropertyChanged 以让 UI 知道您的 gridview 的 ItemSource 已更改?
-
正如我所提到的,我是一个真正的 C# 和 WPF 初学者,我在这里查看了许多解释 INotifyPropertyChanged 的线程,这超出了我的理解范围。