我希望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();
}
}
是否有插入的项目,而不会导致应用程序崩溃的方法吗?
当您尝试“触摸”所选项目时,似乎会出现问题 - 插入使用Array.Copy,因此所选项目被复制,然后在旧索引处替换为新项目,这可能不是由组合框操纵。请注意,当您在0位置选择项目,然后在第一个索引处插入项目时,不会有任何例外。 – Romasz
在插入之前保留选中的项目并将其设置为'null'似乎有效(这在我需要在数据绑定属性实现中处理这种情况时很有用)。随意添加答案:) – Gene