Why does ObservableCollection throws an exception when being modified?

后端 未结 2 702
暗喜
暗喜 2021-01-03 16:11

My application uses a WPF DataGrid. One of the columns is a template column that contains a ComboBox bound to an ObservableCollection

相关标签:
2条回答
  • 2021-01-03 16:40

    Finally I found the reason for the exception. The problem occurs when you are removing the selected item from the list. Below I've posted an incomplete piece of code.

    <!-- XAML -->
    <ListBox ItemsSource="{Binding Rooms}" SelectedItem="{Binding SelectedRoom}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <DockPanel>
                    <Button Content="remove" DockPanel.Dock="Right" Command="{Binding Some Remove Command}" />
                    <TextBlock Text="{Binding Name}" />
                </DockPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    And the view model:

    // View Model
    public ObservableCollection<Room> Rooms { get; private set; }
    public Room SelectedRoom { get; set; }
    
    public RemoveRoom()
    {
        var room = SelectedRoom;
        //SelectedRoom = null; // Uncomment this line to avoid the exception
    
        Rooms.Remove(room);
    }
    

    The solution is to first set the selected item to null (or any other item) before actually removing the item from the list.

    Oliver Hanappi

    0 讨论(0)
  • 2021-01-03 16:50

    Is your Room class object actually instantiated? It looks as if your adding an uninitialised value.

    0 讨论(0)
提交回复
热议问题