更新时间:2022-10-21 13:05:00
Here is a simple example
Your XAML
<Window x:Class="WpfApplication10.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="525"
Height="350"
Loaded="Window_Loaded">
<Grid>
<ListBox ItemsSource="{Binding FileNames}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<Label>Name</Label>
<TextBlock Text="{Binding Name}"/>
<Label>Modified</Label>
<TextBlock Text="{Binding LastModified}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Your Code Behind
public partial class MainWindow : Window
{
public class FileInfo
{
public string Name { get; set; }
public DateTime LastModified { get; set; }
public FileInfo(string name)
{
Name = name;
LastModified = DateTime.Now;
}
}
ObservableCollection<FileInfo> mFileNames = new ObservableCollection<FileInfo>();
public ObservableCollection<FileInfo> FileNames
{
get
{
return mFileNames;
}
}
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem((x) =>
{
while (true)
{
Dispatcher.BeginInvoke((Action)(() =>
{
mFileNames.Add(new FileInfo("X"));
}));
Thread.Sleep(500);
}
});
}
}
If you run this problem you will notice that the listbox updates every half a second with a new item. Basically the key thing to note is that the ObservableCollection can only be updated from the UI thread so if you refactor the above code you need need to somehow use the Dispatcher of the current UI thread to update it