How can I save and load ObservableCollection in MVVM ListView. The error is below..
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
Additional information: Database_MVVM.Model.UserData cannot be serialized because it does not have a parameterless constructor.
In my MainViewModel
public ObservableCollection<UserData> _userDataCollection = new ObservableCollection<UserData>();
public ObservableCollection<UserData> UserDataCollection
{
get { return _userDataCollection; }
set { _userDataCollection = value; }
}
public ICommand SaveCommand
{
get
{
if (saveCommand == null)
{
saveCommand = new DelegateCommand(Save);
}
return saveCommand;
}
}
private void Save()
{
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<UserData>));
using (var sw = new StreamWriter("output.txt"))
{
serializer.Serialize(sw, UserDataCollection);
sw.Close();
}
}
my Model
public class UserData
{
#region Declarations
private string _theEnteredData;
private string _theRandomData;
public UserData(string theEnteredData, string theRandomData)
{
this._theEnteredData = theEnteredData;
this._theRandomData = theRandomData;
}
#endregion
#region Properties
public string theEnteredData
{
get { return _theEnteredData; }
set { _theEnteredData = value; }
}
public string theRandomData
{
get { return _theRandomData; }
set { _theRandomData = value; }
}
#endregion
}
In My Command, I create DelegateCommand.cs
public class DelegateCommand : ICommand
{
private readonly Action _action;
public DelegateCommand(Action action)
{
this._action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this._action();
}
public event EventHandler CanExecuteChanged
{
add
{
}
remove
{
}
}
Once I save the item in listview will automatically clear. Load the save file(txt file) and load it without using openfiledialogbox and with openfiledialog box.
I try using streamwriter and foreach loop to save it as text file but I failed I'm just new to MVVM and still trying to learn it.