2015-10-28 19 views
1

我希望Insert将项目分成ObservableCollection,它在调度程序线程上使用ComboBox绑定(通过使用DispatcherTimer确保)。如果在ComboBox中选择了一个项目,则插入调用将导致应用程序崩溃,并显示不可调试Win32Exception(看起来像this)。当该项目是Add而不是Insert ed时,代码将按预期运行。在ObservableCollection上插入导致Win32Exception

最少的代码示例:

<Page 
x:Class="App1.MainPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:App1" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d"> 

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 

    <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="77,59,0,0" VerticalAlignment="Top" Width="120" 
       ItemsSource="{Binding Data}"> 

     <ComboBox.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding Text}" /> 
      </DataTemplate> 
     </ComboBox.ItemTemplate> 

    </ComboBox> 

    <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="202,58,0,0" VerticalAlignment="Top" Click="button_Click"/> 

</Grid> 

</Page> 

而后面的代码:

public class MyData 
{ 
    public string Text { get; set; } 
} 

public sealed partial class MainPage : Page 
{ 
    public ObservableCollection<MyData> Data { get; set; } 

    public MainPage() 
    { 
     DataContext = this; 

     Data = new ObservableCollection<MyData>() 
     { 
      new MyData { Text = "Lorem" } 
     }; 

     this.InitializeComponent(); 
    } 

    private void button_Click(object sender, RoutedEventArgs e) 
    { 
     var timer = new DispatcherTimer(); 
     timer.Interval = TimeSpan.FromSeconds(1); 
     timer.Tick += (_, __) => { Data.Insert(0, new MyData { Text = "Ipsum" }); /* crash */ }; 
     timer.Start(); 
    } 

} 

是否有插入的项目,而不会导致应用程序崩溃的方法吗?

+0

当您尝试“触摸”所选项目时,似乎会出现问题 - 插入使用Array.Copy,因此所选项目被复制,然后在旧索引处替换为新项目,这可能不是由组合框操纵。请注意,当您在0位置选择项目,然后在第一个索引处插入项目时,不会有任何例外。 – Romasz

+0

在插入之前保留选中的项目并将其设置为'null'似乎有效(这在我需要在数据绑定属性实现中处理这种情况时很有用)。随意添加答案:) – Gene

回答

1

这个问题似乎是,一旦你尝试“触摸”选择的项目出现 - 的ObservableCollection使用List.Insert方法,正如你可以看到在reference使用Array.Copy。选定的项目被复制,然后用旧的索引替换为新项目,这可能不是由Combobox所致,并导致异常。

请注意,当您在0位置选择项目,然后在第一个索引处插入项目时,不会有任何例外。类似的 - 如果没有选择项目,插入任何位置都不会有例外。因此,作为一种解决方法,如果适用,您可以尝试设置Combobox.Selected项目到null开始插入之前,什么可以工作。