当我尝试从单独的线程然后是 ui 线程更新我在 XAML 中使用的 ObservableCollection 时,我得到一个 XamlParseException,它表示必须在与 DependencyObject 相同的线程上创建 DependencySource。我正在使用 Caliurn Micro 将 ViewModel 绑定到视图。
我尝试了几种方法来达到我的目标,下面的方法对我来说似乎是最合理的方法。我将 SyncronizationContext 从 UI 传递给任务,以便它可以在完成繁重的工作后更新 ui。
我究竟做错了什么?
看法
<Window x:Class="QuickScope.Views.NavigatorView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:QuickScope.Views"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:quickScope="clr-namespace:QuickScope"
mc:Ignorable="d">
<Grid>
<TextBox Grid.Row="0"
Name="TextBox"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Center"
Margin="5,0,5,5"
Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
</TextBox>
<Popup PlacementTarget="{Binding ElementName=TextBox}">
<ListView x:Name="ItemList" ItemsSource="{Binding Items}" SelectedItem ="{Binding SelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<Image Source="{Binding IconSource}" Width="20" Height="20"></Image>
<Label Content="{Binding SearchName}"></Label>
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Popup>
</Grid>
视图模型
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using Caliburn.Micro;
using QuickScope.Views;
namespace QuickScope.ViewModels
{
public class NavigatorViewModel : Screen
{
private readonly ItemService _itemService;
public NavigatorViewModel()
{
_itemService = new ItemService();
Items = new ObservableCollection<ItemViewModel>();
}
public ObservableCollection<ItemViewModel> Items { get; }
public ItemViewModel SelectedItem { get; set; }
private string _searchText;
public string SearchText
{
get => _searchText;
set
{
_searchText = value;
NotifyOfPropertyChange(() => SearchText);
UpdateItemList(_searchText);
}
}
private void UpdateItemList(string searchText)
{
Items.Clear();
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
//the long running workload
var items = _itemService.GetByFilter(searchText);
//update the ui
Task.Factory.StartNew(() =>
{
foreach (var item in items)
Items.Add(item);
if (items.Any())
{
SelectedItem = items.First();
NotifyOfPropertyChange(() => SelectedItem);
}
}, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
});
}
}
}
编辑
我尝试了 Shadrix 的方法,但不幸的是它也不起作用。我还尝试了 Peter Dunihos标记重复的答案,但我也没有成功(我得到了与上面描述的相同的 XamlParseException)。
我尝试的最后一件事是 CM 在OnUIThread方法中的构建,它基本上包装了 Dispatcher.CurrentDispatcher。显然(考虑到我最近两次失败的尝试),它也失败了。当前的实现如下所示(我删除了其他不相关的属性和方法):
public class NavigatorViewModel : Screen
{
public NavigatorViewModel()
{
Items = new ObservableCollection<ItemViewModel>();
}
public ObservableCollection<ItemViewModel> Items { get; set; }
public ItemViewModel SelectedItem { get; set; }
private string _searchText;
public string SearchText
{
get => _searchText;
set
{
_searchText = value;
NotifyOfPropertyChange(() => SearchText);
UpdateItemList(_searchText);
}
}
private void UpdateItemList(string searchText)
{
Items.Clear();
var updater = new ItemUpdater();
updater.ItemsUpdated += (s, e) => {
OnUIThread(() =>
{
var items = ((ItemsUpdatedEventArgs) e).Items;
foreach (var item in items)
{
Items.Add(item);
}
NotifyOfPropertyChange(() => Items);
});
};
var updateThread = new Thread(updater.GetItems);
updateThread.Start(searchText);
}
}
public class ItemUpdater
{
public event EventHandler ItemsUpdated;
private readonly ItemService _itemService;
public ItemUpdater()
{
_itemService = new ItemService();
}
public void GetItems(object searchText)
{
var items = _itemService.GetByFilter((string)searchText);
ItemsUpdated?.Invoke(this, new ItemsUpdatedEventArgs(items));
}
}
public class ItemsUpdatedEventArgs : EventArgs
{
public ItemsUpdatedEventArgs(IList<ItemViewModel> items)
{
Items = items;
}
public IList<ItemViewModel> Items { get; }
}
我无法解决这个问题让我发疯,所以如果有人愿意帮助一个年轻的小辈,我会非常感激。:)
您可以在此处找到完整的源代码。
谢谢你们!