繁体   English   中英

在ObservableCollection上插入会导致Win32Exception

[英]Insert on ObservableCollection causes Win32Exception

我想Insert一个项目到ObservableCollection其使用绑定ComboBox调度线程(使用保证DispatcherTimer )。 如果在ComboBox选择了一项,则insert调用将导致应用程序崩溃,并出现不可调试的Win32Exception (如下所示 )。 当该项是Add ed而不是Insert ed时,代码将按预期运行。

最少的代码示例:

<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();
    }

}

有没有一种方法可以插入项目而不会导致应用程序崩溃?

这个问题似乎发生一次尝试选择的项目“触摸” - 的ObservableCollection使用List.Insert方法,正如你可以看到在参考使用Array.Copy。 复制选定的项目,然后在旧索引处将其替换为新的项目,这可能不是Combobox所处理,并且会导致异常。

请注意,当您选择位于0位置的项目,然后在第一索引处插入项目时,也不会例外。 相似-如果未选择任何项目,则在任何位置插入都不会有例外。 因此,作为一种变通办法,如果适用,您可以尝试在开始插入之前将Combobox.Selected项设置为null ,这可能会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM