Why does ObservableCollection throws an exception when being modified?

后端 未结 2 740
暗喜
暗喜 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.

    
    
        
            
                
                    

    And the view model:

    // View Model
    public ObservableCollection 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

提交回复
热议问题