【发布时间】:2013-03-22 18:48:06
【问题描述】:
我有一个程序可以在目录中搜索符合特定条件的文件。这个搜索过程需要 long 时间,所以我必须异步调用它。当搜索算法找到一个文件时,它会触发一个事件。我的MainWindow 实例侦听此事件并需要更新 GUI。如何将这些“添加”文件绑定到ListView?我想我可以使用ObservableCollection<FileInfo> 实例,但我不知道如何绑定它。
我已经删除了所有不相关的控件和代码。这是两个相关文件。
MainWindow.xaml:
<Window x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CR Search" Height="395" Width="525">
<Grid>
<ListView x:Name="Results">
<ListView.View>
<GridView>
<GridViewColumn Header="Filename"/>
<GridViewColumn Header="Directory"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
MainWindow.xaml.cs:
using System.IO;
using System.Threading.Tasks;
public partial class MainWindow
{
private SearchLogic _backgroundSearch;
private async void Search(object sender, RoutedEventArgs e)
{
// TODO: clear Results
_backgroundSearch = new SearchLogic("", new DirectoryInfo("C:\"));
_backgroundSearch.FileAdded += FileAdded;
await Task.Run(new Action(_backgroundSearch.Search));
}
private void FileAdded(object sender, FileAddedEventArgs eventArgs)
{
// TODO: add eventArgs.File to Results
// eventArgs.File is an instance of FileInfo
}
}
【问题讨论】:
标签: c# .net wpf listview data-binding