I have WPF application where I am following MVVM. I have a class called Session as follows: Session.cs
public class Session:ObservableCollection<Session>
{
public int value { get; set; }
public string name { get; set; }
}
public class CustomSession:DependencyObject
{
public static readonly DependencyProperty SessionCollectionProperty =
DependencyProperty.Register("SessionCollection", typeof(Session), typeof(CustomSession), new PropertyMetadata());
public Session SessionCollection
{
get { return (Session)GetValue(SessionCollectionProperty); }
set { SetValue(SessionCollectionProperty, value); }
}
}
I have ViewModel as follows: ViewModel.cs
public class ViewModel:BindableBase
{
private ObservableCollection<Session> _sessions;
public ObservableCollection<Session> sessionsCollection
{
get { return _sessions; }
set { SetProperty(ref _sessions, value); }
}
public ViewModel()
{
sessionsCollection = allSessions();
}
public ObservableCollection<Session> allSessions()
{
CustomSession custom = new CustomSession();
custom.SessionCollection.Add(new Session() { name = "LocateSession", value = 10 }); //System.Null Reference Exception.
custom.SessionCollection.Add(new Session() { name = "TrackSession", value = 20 });
custom.SessionCollection.Add(new Session() { name = "MonitorSession", value = 25 });
custom.SessionCollection.Add(new Session() { name = "MassSnapshot", value = 18 });
custom.SessionCollection.Add(new Session() { name = "MassContinuous", value = 9 });
return custom.SessionCollection;
}
}
I have a UI where I want to bind this Observable Collection. Whenever I try to add in an item like custom.SessionCollection.Add(new Session() { name = "LocateSession", value = 10 }); I get Null Reference exception. I want to populate the ObservableCollection from the ViewModel. How do I do it. Please help.