I'm trying to learn c#/WPF/MVVM by converting a sample WPF app to MVVM. This app opens a xml file for editing and then saves it. The app preforms well until I try to save the file, I'm getting an InvalidCastException. Here is some code
mDataSource.cspublic static List<MediaItem> Load(string filename)
{
var mediafiles = XDocument.Load(filename).Root.Elements("style").Elements("item").Select(
x => new MediaItem(
(string)x.Element("title"),
(string)x.Element("artist"),
(string)x.Element("year")));
return mediafiles.ToList();
}
MainViewModel.cs - Load the xml file
public void LoadList(string filename)
{
this.mediafiles = new ObservableCollection<MediaItemViewModel>();
List<MediaItem> mediabaseList = mDataSource.Load(filename);
foreach (MediaItem mediaitem in mediabaseList)
{
this.mediafiles.Add(new MediaItemViewModel(mediaitem));
}
this.collectionView = CollectionViewSource.GetDefaultView(mediafiles);
if (this.collectionView == null)
throw new NullReferenceException("collectionView");
this.collectionView.CurrentChanged += new EventHandler(this.OnCollectionViewCurrentChanged);
}
Saving the file
private void Save(ICollectionView collectionView)
{
mDataSource mds = new mDataSource();
mds.Save(this.collectionView);
}
mDataSource - Saving the file, during debugging data shows up properly everywhere but the exception comes on the line - MediaItem mi = (MediaItem)mediaitem; {"Unable to cast object of type 'mList.ViewModels.MediaItemViewModel' to type 'mList.Models.MediaItem'."}
public void Save(ICollectionView collectionView)
{
XDocument xdoc = new XDocument();
XElement xeRoot = new XElement("art");
XElement xeSubRoot = new XElement("style");
foreach (var mediaitem in collectionView)
{
MediaItem mi = (MediaItem)mediaitem;
XElement xRow = new XElement("item");
xRow.Ad开发者_C百科d(new XElement("title", mi.Title));
xRow.Add(new XElement("artist", mi.Artist));
xRow.Add(new XElement("year", mi.Year));
xeSubRoot.Add(xRow);
}
xeRoot.Add(xeSubRoot);
xdoc.Add(xeRoot);
xdoc.Save(filename);
}
Thank You
ICollectionView (which shouldn't be referenced in your VM) contains a bunch of MediaItemViewModels.
this.mediafiles.Add(new MediaItemViewModel(mediaitem));
So, you need to get the MediaItem
that is wrapped by the given MediaItemViewModel
. You didn't include that code, so I can't tell you where the original MI is stored.
foreach (var mediaitem in collectionView.OfType<MediaItemViewModel>())
{
MediaItem mi = mediaitem.ThisPropertyContainsTheWrappedMediaItem;
精彩评论