views:

60

answers:

2

I have an ObservableCollection which is dataContext for my treeview when I try to remove an Item from ObservableCollection I will get an error that Object reference not set to an instance of an object . can you please tell me why this error is happening and what is the solution

thanks

EDIT 1: The code is something like :

class MyClass : INotifyPropertyChanged
{
    //my class code here
}
public partial class UC_myUserControl : UserControl
{
    private ObservableCollection<MyClass> myCollection = new ObservableCollection<MyClass>();
    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        myCollection.add(new myClass);
        myTreeView.DataContext = myCollection ;
    }
    private void deleteItem()
    {
        myCollection.RemoveAt(0);
        //after removing I get error Which I guess should be something related 
        //to interface update but I don't know how can I solve it
    }
}

Exception Detail : System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="PresentationFramework"

EDIT 3: I have a style which is for my treeitem to keep the treeitems expanded

<Style TargetType="TreeViewItem">
      <Setter Property="IsExpanded" Value="True" />
</Style>

and with commenting this part I wont get any error !!! Now I want to change my question to why having this style is causing error ?

A: 

As I said in EDIT2 the reason is the style that I have for expanding all treeitems with removing the style the isue is solved .thanks for all the comments .

<Style TargetType="TreeViewItem">
      <Setter Property="IsExpanded" Value="True" />
</Style>
Asha
This should really have been an update to your question rather than a separate answer.
ChrisF
A: 

I had similar problem when I have also binding to selected item in the collection and I tried to delete the selected item. I had to first change the selected item and then delete it.

Lukas Cenovsky