WPF targetinvocationexception was unhandled when try to populate ObservableCollection

561 views Asked by At

I have my object that i want to insert into ObservableCollection:

public ObservableCollection<MyData> collection{ get; set; }

this.DataContext = this;
collection= new ObservableCollection<MyData>();

Now here i have Array with my objects:

MyData[] array...

So here i try to add 1 object into my ObservableCollection

collection.Add(array[0]);

And received the targetinvocationexception exception

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

2

There are 2 answers

0
Mohsen On

Try it : (My answerd by this method) :

In outside scope,declare public :

public ObservableCollection<MyData> collection{ get; set; }

In Contructor :

this.DataContext = this;
collection= new ObservableCollection<MyData>();

MyDataArray is :

MyData[] array =
        {
            new MyData { MyProp = "A" },
            new MyData { MyProp = "B" },
            new MyData { MyProp = "C" }
        };

In button for add to list :

collection.Add(array[1]);

MyData class is :

public class MyData
{
    public string MyProp { get; set; }
}
0
Ivanaki Yakudzio On

Usually this error appears if you associate the DataContext before calling InitializeComponent method. For example

public MainWindow() {
   timerViewModel = new TimerViewModel(new MyDateTime());
   timerLabel.DataContext = timerViewModel; //error
   InitializeComponent();    
}

public MainWindow() {
   timerViewModel = new TimerViewModel(new MyDateTime());
   InitializeComponent();
   timerLabel.DataContext = timerViewModel; //Ok
}