我希望将一个项目绑定到一个Insert中,这个ObservableCollection使用调度程序线程上的ComboBox绑定(通过使用DispatcherTimer来确保)。插入调用将导致应用程序与不可调试的Win32Exception (类似于这)崩溃,如果在ComboBox中选择了项。当项目是Added而不是Inserted时,代码将按预期运行。
最小代码示例:
<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();
}
}有没有一种方法可以插入该项目而不会导致应用程序崩溃?
发布于 2015-10-28 12:18:00
当您尝试“触摸”选定的项时,问题似乎就会发生-- ObservableCollection使用List.Insert方法,正如您在参考文献上看到的那样,它使用Array.Copy。所选项目将被复制,然后在旧索引处替换为新项,这可能不会由Combobox处理,从而导致异常。
请注意,当您在0位置选择item,然后在第一个索引处插入item时,也不会有例外。相似--如果没有选择任何项目,在任何位置插入时都不会有例外情况。因此,作为一种解决方法,如果可以应用,可以尝试在开始插入之前将Combobox.Selected项设置为null。
https://stackoverflow.com/questions/33389957
复制相似问题