Click here to Skip to main content
15,880,279 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good Morning.

I have the following problem:

I got a SaveData class which should serialize an ObservableCollection<personmodel> to a XML document.
The ViewModel contains this collection while PersonModel is Model class.
I can not reference the Model in the SaveData class because this would cause an infinite dependency.

When I invoke the SerializeData() method in the ViewModel it says that it can not assign the ObservableCollection<personmodel> to the parameter type ObservableCollection<object>.
Seems logical...but how is it possible to cast the ObservableCollection?

Code for the SaveData class:
C#
public class SaveData
{
    private XmlSerializer serializer;
    private string saveLogPath;

    public SaveData()
    {
        serializer = new XmlSerializer(typeof(ObservableCollection<object>));
    }

    private string GetSaveLogPath()
    {
        const string saveLog = "SaveLog.xml";
        var dir = AppDomain.CurrentDomain.BaseDirectory+saveLog;
        return dir;
    }

    public void SerializeData(ObservableCollection<object> dataToSerialize)
    {
        saveLogPath = GetSaveLogPath();

        if (File.Exists(saveLogPath))
        {
            var stream = new FileStream(saveLogPath, FileMode.Open);
            serializer.Serialize(stream,dataToSerialize);
        }
        else
        {
            File.Create(saveLogPath);
            var stream = new FileStream(saveLogPath, FileMode.Open);
            serializer.Serialize(stream, dataToSerialize);
        }
    }
}


Code for the ViewModel:
C#
class MainWindowViewModel : INotifyPropertyChanged
{
     private ObservableCollection<PersonModel> personList;

     public MainWindowViewModel()
     {
          personList = new ObservableCollection<PersonModel>();
     }

     public void SaveData(object parameter)
        {
            serializer = new SaveData();
            serializer.SerializeData(PersonList); //Error Occurs here
        }
}


Any help is appreciated.
Thanks in advance.
Posted
Updated 7-Oct-13 22:20pm
v2

1 solution

I faced the same problem in my life and I searched a lot but I didn't found any good solution for the same problem.

Then I cast it by using foreach loop.
You can also do the same using foreach loop.

Regards,
CodeBlack
 
Share this answer
 
Comments
Marvin Ma 8-Oct-13 5:49am    
Thank you for your answer...this worked for me :)
CodeBlack 8-Oct-13 6:57am    
my pleasure :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900