i just started to play a little bit with Binary Serialization.
I have a class "SerializeMe" which i want to serialize:
[Serializable]
public class ViewModelBase : INotifyPropertyChanged
{
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void RaisePropertyChanged(
[CallerMemberName]string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
[Serializable]
public class SerializeBase : ViewModelBase
{
.
.
.
}
Class i want to serialize:
[Serializable]
public class SerializeMe : SerializeBase
{
.
.
.
}
In my MainViewModel i have an ObservableCollection of type "SerializeBase" and a Method which serializes the first item in the collection:
public class MainViewModel : ViewModelBase
{
private ObservableCollection<SerializeBase> _workspaces;
public MainViewModel()
{
_workspaces = new ObservableCollection<SerializeBase>
// EDIT
{
new SerializeMe(),
new SerializeMe()
}
// EDIT END
}
public ObservableCollection<SerializeBase> Workspaces
{
get { return _workspaces; }
set
{
if (value == _workspaces)
return;
_workspaces = value;
RaisePropertyChanged();
}
}
public void SerializeFirst()
{
var fisrtItem = _workspaces.FirstOrDefault();
if (firstItem == null)
return;
using(var stream = new FileStream("file.bin", FileMode.Create))
{
new BinaryFormatter().Serialize(stream, firstItem);
}
}
}
All this works just if i mark my MainViewModel as Serializable.
This works:
namespace Namespace
{
[Serializable]
public class MainViewModel : ViewModelBase
.
.
.
This not:
namespace Namespace
{
public class MainViewModel : ViewModelBase
.
.
.
Error detail: The type MainViewModel... is not marked as Serializable.
Could someone explain why my MainViewModel has to be serializable? I don't get it.
Thanks.