我认为这是一个相当标准的设置,有一个ListBox支持ObservableCollection.
我有一些工作要处理可能需要花费大量时间(超过几百毫秒)的Things,ObservableCollection所以我想将其卸载到Task(我本来也可以使用BackgroundWorker)以免冻结用户界面.
什么奇怪的是,当我CollectionViewSource.GetDefaultView(vm.Things).CurrentItem开始之前Task,一切正常,但是如果发生这种情况时的Task那么CurrentItem似乎总是指向的第一个元素ObservableCollection.
我已经制定了一个完整的工作示例.
XAML:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<ToolBar DockPanel.Dock="Top">
<Button Content="Click Me Sync" Click="ButtonSync_Click" />
<Button Content="Click Me Async Good" Click="ButtonAsyncGood_Click" />
<Button Content="Click Me Async Bad" Click="ButtonAsyncBad_Click" />
</ToolBar>
<TextBlock DockPanel.Dock="Bottom" Text="{Binding Path=SelectedThing.Name}" />
<ListBox Name="listBox1" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=Things}" SelectedItem="{Binding Path=SelectedThing}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</ListBox.ItemTemplate> …Run Code Online (Sandbox Code Playgroud)