One of the major difficulties in encapsulating a model is that the model often has attributes that are called "derived attributes" by the Unified Modeling Language (UML. For example, the person class may have the birthdate attribute and the derived age attribute. The age attribute is read-only and automatically calculates the age based on the birthday and current date:
Public class person: domainobject {public datetime birthdate {Get; set;} public int age {get {var today = datetime. Now; // simplified DEMO code! Int age = today. Year-This. birthdate. Year; return age ;}}...
When the birthdate attribute is changed, the age attribute is also changed because the age is calculated by mathematical means based on the birthday. Therefore, when setting the birthdate attribute, the viewmodel class must simultaneously trigger a property change event for the birthdate attribute and age attribute. With the dynamic viewmodel method, you can explicitly express this internal property relationship in the model to automatically complete this operation.
First, you need a custom feature to record the property relationship:
[Attributeusage (attributetargets. property, allowmultiple = true)] public sealed class affectsotherpropertyattribute: attribute {public affectsotherpropertyattribute (string otherpropertyname) {This. affectsproperty = otherpropertyname;} Public String affectsproperty {Get; private set ;}}
I set allowmultiple to true to enable one attribute to affect multiple other attributes. This feature is used to directly write the relationship between birthdate and age into the modelCode, This operation is very simple:
[Affectsotherproperty ("Age")] public datetime birthdate {Get; set ;}
To use this new model metadata in the dynamic viewmodel class, I can add three lines of code in the trysetmember method to make it as follows:
Public override bool trysetmember (setmemberbinder binder, object Value) {... var affectsprops = property. getcustomattributes (typeof (affectsotherpropertyattribute), true );
Foreach (affectsotherpropertyattribute otherpropertyattr in affectsprops) This. raisepropertychanged (otherpropertyattr. affectsproperty );}
Because the getcustomattributes method has obtained the reflected property information, it can return any affectsotherproperty feature on the model property. The Code then cyclically traverses these features and triggers attribute change events for each feature. Therefore, the changes made to the birthdate attribute through viewmodel will now automatically trigger a property change event for both the birthdate and age attributes.
It is important to realize that if you perform explicit programming on an attribute of the dynamic viewmodel class (more likely the viewmodel class derived from a specific model, instead of calling the trygetmember and trysetmember methods, DLR calls these attributes directly. In this case, you will lose this automatic behavior. However, you can easily refactor the code so that custom attributes can also use this function.
Let's go back to the Data Binding problem on the deep nested attribute (in this case, viewmodel is the current WPF data context). The Code is as follows:
{Binding wrappeddomainobject. Address. Country}
Using Dynamic proxy properties means that domain objects encapsulated at the underlying layer are no longer directly provided, so data binding may actually be as follows:
{Binding address. Country}
In this case, the address attribute can still directly access the address instance of the underlying model. But now, if you want to introduce viewmodel around address, you only need to add new attributes to the person viewmodel class. The new address attribute is very simple:
Public dynamicviewmodel address {get {If (addressviewmodel = NULL) addressviewmodel = new dynamicviewmodel (this. Person. Address); Return addressviewmodel;} private dynamicviewmodel addressviewmodel;
You do not need to change any XAML data binding because the attribute is still named address, but DLR now calls the new actual attribute instead of the dynamic trygetmember method. (Note that the delay instantiation in this address attribute is NOT thread-safe. However, only the views that are accessing the viewmodel and WPF/Silverlight views are single-threaded, so this is not a problem .)
This method can be used even when the model implements inotifypropertychanged. Viewmodel will notice this situation and choose not to use a proxy to trigger a property change event. In this case, it listens to these events from the underlying model instance, and then automatically raises the event again. In the constructor of the dynamic viewmodel class, I executed the check and wrote down the result:
Public dynamicviewmodel (domainobject model) {contract. Requires (model! = NULL, "cannot encapsulate a null model"); this. modelinstance = model; // raises its own property changed events if (model is inotifypropertychanged) {This. modelraisespropertychangedevents = true; var raisespropchangedevents = model as inotifypropertychanged; raisespropchangedevents. propertychanged + = (sender, argS) => This. raisepropertychanged (ARGs. propertyname );}}
If (this. modelraisespropertychangedevents = false) This. raisepropertychanged (property. Name );
Therefore, you can use dynamic proxy properties to remove standard proxy properties, greatly simplifying the viewmodel layer. This greatly reduces coding, testing, documentation, and long-term maintenance. You do not need to update the viewmodel layer to add new attributes to the model unless the new attributes have special view logic. In addition, this method can solve problems such as association attributes. The commonly used trysetmember method can also help you implement the "undo" function, because all the attribute changes executed by the user will flow through the trysetmember method.
Advantages and disadvantages
Due to performance issues, many developers are reluctant to use reflection (and DLR ). In my work, I have not found any problems. The performance loss caused by setting a single attribute in the UI may not be noticed by the user. Of course, this may not apply to highly sensitive interactive UIS, such as multi-touch design surfaces.
The only major performance problem occurs when a view with a large number of fields is filled for the first time. Ease of use considerations naturally limit the number of fields displayed on the screen. Therefore, the performance of initial data binding with this DLR method is hard to detect.
However, you should always carefully monitor performance and understand the relationship between performance and user experience. The preceding simple method can be rewritten through reflection cache. For more details, see Joel pobar'sArticle.
Some people think that using this method will have a negative impact on the readability and maintainability of the Code. This objection is justified because the view layer seems to be an attribute that does not actually exist on the reference viewmodel. However, I believe that the benefits of eliminating most manually written proxy attributes far exceed those brought about by them, especially when viewmodel has a well-developed document.
The dynamic proxy attribute method does not degrade or cancel the ability to disrupt the model layer, because the attributes on the model are currently referenced in the XAML by name. Using traditional proxy attributes does not limit your ability to disrupt the model. This is because the attributes are directly referenced andProgram. However, this is basically useless because most of the disrupted tools cannot process XAML/baml. In both cases, the code cracker can start with XAML/baml and gradually enter the model layer.
Finally, this method may be abused because model attributes have security-related metadata and viewmodel is expected to be responsible for implementing security issues. Security does not seem to be a specific responsibility of the view. I believe this gives the viewmodel too much responsibility. In this case, it may be more appropriate to apply the Aspect-Oriented Method in the model.
----------------------------------------------------------------------------
Set
Collection is one of the most difficult and unsatisfactory aspects of the mvvm design model. If the set in the underlying model is changed by the model, the viewmodel is responsible for conveying the change in some way, so that the view can change itself accordingly.
Unfortunately, the model may not publicly implement the set of inotifycollectionchanged interfaces. In. NET Framework 3.5, this interface is located in system. Windows. dll, and we strongly recommend that you do not use this library in model. Fortunately, in. NET Framework 4, this interface has been migrated to system. dll, so it is much more natural to use a visible set in the model.
The visible set in the model provides a new opportunity for model development and can be used in Windows Forms and Silverlight applications. At present, this is my preferred method because it is simpler than any other method. I'm glad that the inotifycollectionchanged interface has moved to a more common assembly.
If the set is not visible in the model, it is best to provide another mechanism (most likely a Custom Event) on the model to indicate when the set was changed. This can be done through the unique method of model. For example, if the person class has an address set, it can provide the following events:
Public event eventhandler <addresseschangedeventargs> newaddressadded; public event eventhandler <addresseschangedeventargs> addressremoved;
It is best to trigger a custom set event specially designed for the WPF viewmodel. However, it is still difficult to publish changes to the set in viewmodel. Similarly, the only way is to trigger a property change event on the attributes of the entire viewmodel set. This solution is at best unsatisfactory.
Another problem with the set is to determine when or whether to wrap each model instance into a set in the viewmodel instance. For small sets, viewmodel may expose a new visible set and copy each item in the underlying model set to the viewmodel visible set, in this way, each model item is packaged into the set in the corresponding viewmodel instance during runtime. Viewmodel may need to listen for set change events to pass user changes back to the underlying model.
However, for large sets, it may be displayed in some form of virtualization panel, so the simplest and most practical method is to directly expose the model object.
Instantiate viewmodel
Another issue rarely discussed in the mvvm design pattern is where and when viewmodel instances should be instantiated. This issue is often overlooked when discussing similar design patterns (such as MVC.
I prefer to write a single viewmodel instance to provide the main viewmodel object, so that the view can easily retrieve all other viewmodel objects as needed. This type of Main Control viewmodel Object usually provides command implementation, so view supports opening documents.
However, most of the applications I have participated in provide a document-centric interface, and usually use an option-style workspace similar to Visual Studio. Therefore, in the viewmodel layer, I want to take the document as an example, and the document provides one or more viewmodel objects that wrap a specific model object. The standard wpf commands in the viewmodel layer can then use the persistence layer to retrieve necessary objects, encapsulate them into the viewmodel instance, and then create the viewmodel Document Manager to display them.
Internal class opennewpersoncommand: icommand {... // open a new person in a new window. public void execute (object parameter) {var person = new mvvmdemo. model. person (); var document = new persondocument (person); documentmanager. instance. activedocument = Document ;}}
The viewmodel Document Manager referenced in the last line is a single instance for managing all open viewmodel documents. The question is, how does one display the set of viewmodel documents in the view?
The built-in WPF tab control does not provide such a powerful multi-document interface that you want to obtain. Fortunately, third-party dock and option-card work zone products are available. Most of them try their best to imitate the option-style document appearance of Visual Studio, including the tool window that can be docked, split view, CTRL + TAB pop-up window (with micro-document view) and other functions.
Unfortunately, most of these components do not provide built-in support for the mvvm design mode. This does not matter, because you can easily apply the adapter design mode and link the viewmodel document manager to a third-party view component.
Document Manager Adapter
The adapter design shown in Figure 2 ensures that the viewmodel does not need any reference to the view, so it meets the main goal of the mvvm design pattern. (In this case, the document concept is defined in the viewmodel layer, rather than in the model layer, because this is a pure UI concept .)
Figure 2 Document Manager view Adapter
Viewmodel Document Manager is responsible for maintaining the set of open viewmodel documents and understanding which documents are currently active. This design enables the viewmodel layer to use the document manager to open and close documents and change activity documents without understanding the view. The viewmodel end of this method is quite simple. The viewmodel Class 3 in the sample application is shown in.
Figure 3 Document Manager and document class at the viewmodel Layer
The document base class provides several internal lifecycle methods (activated, lostactivation, and documentclosed) that are called by the Document Manager to keep the document up-to-date. This document also implements the inotifypropertychanged interface, so it supports data binding. For example, the adapter binds the title attribute data of the view document to the documenttitle attribute of the viewmodel.
The most complex part of this method is the adapter class, And I provide a copy that works correctly in the project that is included in this article. The adapter subscribes to events on the document manager and uses these events to keep the option-style workspace controls up-to-date. For example, when the document manager instructs you to open a new document, the adapter will receive an event, wrap the viewmodel document to the required WPF control, and then display the control in the option-based workspace.
The adapter has another task: to synchronize viewmodel Document Manager with user operations. Therefore, the adapter must also listen for events from the option-style workspace control to notify the document manager when the user changes the activity document or closes the document.
This logic is not very complex, but there are still some precautions. In some cases, the code can be re-entered, so this situation must be well handled. For example, if viewmodel uses Document Manager to close a document, the adapter will receive an event from Document Manager and close the actual document window in the view. This causes the option-style workspace control to also raise a document Close event, and the adapter will also receive this event, and the adapter's event handler will of course notify the document manager that the document should be closed. This document has been closed, so the document manager must be able to support this situation.
Another difficulty is that the view adapter must be able to link the option-style document control of the view to the viewmodel Document Object. The most reliable solution is to use WPF-related dependency attributes. The adapter declares a private dependency attribute to link the View window control to its viewmodel document instance.
In the example project in this article, I used an open-source option-card workspace component avalondock, so my dependency attributes are similar to Figure 4.
Figure 4 link the view control and viewmodel document
Private Static readonly dependencyproperty viewmodeldocumentproperty = dependencyproperty. registerattached ("viewmodeldocument", typeof (document), typeof (documentmanageradapter), null); Private Static document getviewmodeldocument (avalondock. managedcontent viewdoc) {return viewdoc. getvalue (viewmodeldocumentproperty) as document;} Private Static void setviewmodeldocument (avalondock. managedcontent viewdoc, document) {viewdoc. setvalue (viewmodeldocumentproperty, document );}
When the adapter creates a new view window control, it sets the relevant properties on the new window control to the underlying viewmodel document (see figure 5 ). You can also see that the title data binding is configured here, and how the adapter configures the data context and content of the view document control.
Figure 5 set Related Properties
Private avalondock. documentcontent createnewviewdocument (document viewmodeldocument) {var viewdoc = new avalondock. documentcontent (); viewdoc. datacontext = viewmodeldocument; viewdoc. content = viewmodeldocument; binding titlebinding = new binding ("documenttitle") {source = viewmodeldocument}; viewdoc. setbinding (avalondock. managedcontent. titleproperty, titlebinding); viewdoc. closing + = onuserclosingdocument; documentmanageradapter. setviewmodeldocument (viewdoc, viewmodeldocument); Return viewdoc ;}
Method of the viewmodel document. The actual data template of the viewmodel document is located in the resource dictionary contained in the main XAML window.
I have successfully used this viewmodel Document Manager method in WPF and Silverlight. The only view-Layer Code is an adapter, which can be easily tested and then followed. This method makes the viewmodel and view completely independent. I have replaced my option-card workspace component supplier. This change only creates a minimum change in the adapter class, while viewmodel and model are completely unaffected.
The ability to process documents in the viewmodel layer seems very simple, and it is very easy to implement viewmodel commands similar to my demo. Obviously, the viewmodel document class is also very suitable for providing document-related icommand instances.
View is mounted to these commands, and the advantages of the mvvm design mode are also fully realized in this process. In addition, the viewmodel Document Manager method can work with a single instance method if you need to display data before creating any document (possibly in a foldable tool window.
Summary
The mvvm design mode is a powerful and practical model, but no one can solve all problems. As I demonstrated in this article, combining the mvvm mode and target with other modes (such as the adapter and Single Instance) can leverage the new one. NET framework 4 functions (such as dynamic scheduling) can also solve many common problems encountered when implementing the mvvm design mode. By using mvvm in this way, you can create more elegant and easy-to-maintain WPF and Silverlight applications.
Download the sample source code or material in this article