I want to change ListBox ItemsSource without UI freezing. For this challenge, I wrote the code that you see below;
When User Click The Button
Thread th = new Thread(DisplayFilesAsync);
th.Start(new object[] { FolderPath, fdv.FileType });
Async Method
private void DisplayFilesAsync(object param)
{
object[] args = param as object[];
string searchText = Convert.ToString(args[0]);
FileType type = (FileType)args[1];
IEnumerable<FileListItem> list = uDirectoryHelper.GetFileFromFolder(searchText, type);
Dispatcher.BeginInvoke(new Action<IEnumerable<FileListItem>>(DisplayFiles), DispatcherPriority.Background, new object[] { list });
}
Change The ItemsSource
private void DisplayFiles(IEnumerable<FileListItem> fileList)
{
lstFiles.ItemsSource = fileList;
}
In the last method, if I change directly ItemSource of ListBox, program isn't break up but when program pass to closed curly brackets of the method, is break up and throw an Must create DependencySource on same Thread as the DependencyObject exception.
if I changed that; it's break up on closed curly brackets again, not over the ADD method and throw an same exception.
private void DisplayFiles(IEnumerable<FileListItem> fileList)
{
foreach (FileListItem item in fileList)
{
lstFiles.Items.Add(item);
}
}
But if I change the code like that, it's work perfectly and add items to my listbox.
foreach (FileListItem item in fileList)
{
lstFiles.Items.Add("EXAMPLE");
}
I'm really don't understand to my missing. Why I can add to some string but I can't add to my FileListItem class. What am I missing? I've tried a lot of different code but it's always break on closed curly braces NOT OVER THE ASSIGMENT LINE.
I'm really need to help. Thanks for answers. Have good day, good works.