How to use MVVM when the Model is created by View

2019-08-30 09:42发布

问题:

I'm now trying to use the MVVM approach to display some hierarchical data but until now, I didn't implement any specific design pattern.

As simply as I can explain, I have 2 class libraries.

  1. Log.cs
  2. Backup.cs

And I have my WPF project.

Simply put, the Backup class performs some copy and paste functions. Each copy and paste is logged (using the Log class).

Currently, the logs (List) are stored in memory (and this is where maybe there is an issue). When the operation is complete (all backups are finished), I want the Logs to be displayed. My backup.cs class creates an instance of the MainWindow and passes the List<Log> object as a constructor, and I bind it to the data context. This works fine.

However, I now want to use the MVVM approach since I want to use 2 way binding (I want to filter by log status (success or fail (or other states)).

So, does any one feel this is possible with my current design or is the only way forward to be saving the logs as an XML file (or text or similar) just so my Model can be created (using LinqToXml)? Or is there a different approach?

回答1:

I think you can use your current design and still implement a MVVM approach, that's not to say that you're not going to need to do some significant work.

But you seem to be implying that to use an MVVM pattern, you need to have some connection to a database, and this isn't the case. In your case your model is your Log class and [potentially] the Backup class.

Your view model would accept an instance of the Log class, which is where all the data that your UI wants to present lives, and then exposes the other UI properties necessary to facilitate the rest of your UI, such as the filter properties, sorting properties, etc.



标签: .net wpf mvvm