WPF WITH MVVM AN INTRODUCTION TO MVVM USING

  • Slides: 22
Download presentation
WPF WITH MVVM AN INTRODUCTION TO MVVM USING WPF NISCHAL S

WPF WITH MVVM AN INTRODUCTION TO MVVM USING WPF NISCHAL S

PRIOR UNDERSTANDING • Understanding C# programming language • Understanding on basic WPF concepts including

PRIOR UNDERSTANDING • Understanding C# programming language • Understanding on basic WPF concepts including binding • Basic understanding of design patterns and it’s purpose

Topics • • Understanding MVVM WPF Binding Connecting Model, View and View. Model with

Topics • • Understanding MVVM WPF Binding Connecting Model, View and View. Model with Bindings Data templates to represent Model data Command communication Data validations in Model Dependency Injection Demo

Understanding MVVM • Similar concepts to MVC pattern • Three components • • •

Understanding MVVM • Similar concepts to MVC pattern • Three components • • • Model – Data representation View – UI presentation, display formatted data View. Model – link between model and view, handles events • Testability, Maintainability and Extensibility

Understanding MVVM • View The view is primarily responsible for defining structure, layout and

Understanding MVVM • View The view is primarily responsible for defining structure, layout and appearance of data that user sees. It is purely XAML with limited code behind logic. View get’s it data from the View. Model through binding collection to invoking method in View. Model. When user interacts on the View, such a button click/item selection, then the code in View. Model is executed. This is possible when control’s command is data bound to ICommand property of the View. Model. The view references the view model through its Data. Context property. The controls in the view are data bound to the properties and commands exposed by the view model. • Model This is the domain model that contains data definition with validations. the model implements the facilities that make it easy to bind to the view. Model supports property and collection changed notification through the INotify. Property. Changed and INotify. Collection. Changed interfaces. Models classes that represent collections of typically Observable. Collection<T> class, provides an implementation of the INotify. Collection. Changed interface. Model may also support data validation and error reporting through the IData. Error. Info (or INotify. Data. Error. Info) interfaces. The IData. Error. Info and INotify. Data. Error. Info interfaces allow WPF data binding to be notified when values change so that the UI can be updated. They also enable support for data validation and error reporting in the UI layer.

Understanding MVVM View. Model The view model acts as an intermediary between the view

Understanding MVVM View. Model The view model acts as an intermediary between the view and the model, and is responsible for handling the view logic. The view model then provides data from the model in a form that the view can easily use. The view model retrieves data from the model and then makes the data available to the view, and may reformat the data in a way simpler for the view to handle. The view model also provides implementations of commands that a user of the application initiates in the view. The view model typically does not directly reference the view. It implements properties and commands to which the view can data bind.

WPF BINDING – SOME INTRODUCTION Data binding allows the flow of data between UI

WPF BINDING – SOME INTRODUCTION Data binding allows the flow of data between UI elements and data object on user interface. When the data provides the proper notifications, then, when the data changes its value, the elements that are bound to the data reflect changes automatically in UI. Also if an outer representation of the data in an element changes, then the underlying data can be automatically updated to reflect the change Types of Binding: • One. Way- binding causes changes to the source property to automatically update the target property, but changes to the target property are not propagated back to the source property. Control being is implicitly read-only. • Two. Way- binding causes changes to either the source property or the target property to automatically update the other. Suitable when control bound is editable forms or other fully-interactive UI scenarios. • One. Way. To. Source- is the reverse of One. Way binding; it updates the source property when the target property changes. One example scenario is if you only need to re-evaluate the source value from the UI.

WPF BINDING – SOME INTRODUCTION Update. Source. Trigger: • Bindings that are Two. Way

WPF BINDING – SOME INTRODUCTION Update. Source. Trigger: • Bindings that are Two. Way or One. Way. To. Source lis ten for changes in the target property and propagate them back to the source. Edit the text of a Text. Box to change the underlying source value. • • • Lost. Focus (default for Text. Box. Text) Property. Changed Explicit - When the application calls Update. Source for that control, submit button clicked In this example the Text. Box is binded to properties of Employee class like First. Name, Last. Name and Department.

Connecting Model, View and View. Model 1 2 1. A Model defines the data.

Connecting Model, View and View. Model 1 2 1. A Model defines the data. Note that we have implemented the interface INotify. Property. Changed by implementing method Raise. Property. Changed. The method raises event that property has been updated. 2. A View. Model is defined to create a collection which is Observable. Collection<T>. This collection dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed

Connecting Model, View and View. Model 4 3 Two ways to construct view: 3.

Connecting Model, View and View. Model 4 3 Two ways to construct view: 3. The View, contains the setting for Data. Context, It is null from start and should be assigned to source of your binding, which is View. Model. Construct view in XAML. 4. Another Option is to set data source from code behind of user control. Construct view from code behind. Demo: 1

DATA TEMPLATES TO REPRESENT DATA MODEL 1 • Templates customize the visual behaviour and

DATA TEMPLATES TO REPRESENT DATA MODEL 1 • Templates customize the visual behaviour and visual appearance of a control. • Resource Dictionary could contains list of templates to be used by element that uses data binding. • Data. Template has a key template. Display, used by the List Control to set that particular template. • This is explicit template, where in template key is used by the List Control. Demo: 2

DATA TEMPLATES TO REPRESENT DATA MODEL 2 • To make the template application implicit

DATA TEMPLATES TO REPRESENT DATA MODEL 2 • To make the template application implicit to controls using the same data, then template could be applied to Model. • To make this an implicit, remove the Item. Template property from a listbox. Add a Data. Type property in our template definition and make sure to include the namespace for model. • Here data template is applied to all employee data implicitly. Demo: 3

COMMAND COMMUNICATION • Behavioural design patterns are “Design patterns that identify common communication patterns

COMMAND COMMUNICATION • Behavioural design patterns are “Design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication. ” • In short it is concerned with communication between objects. One such behavioural pattern is Command Pattern. Here Command objects encapsulate command it’s parameters. • Definition*: “The Command pattern encapsulates a request in an object so that it can be passed as a parameter, stored on a history list, or manipulated in other ways. ” Demo: 5 *GAMMA, E. (1995). Design patterns: elements of reusable object-oriented software. Reading, Mass, Addis

COMMAND COMMUNICATION 2 1 • Create a Relay. Command class and implement the methods

COMMAND COMMUNICATION 2 1 • Create a Relay. Command class and implement the methods of Interface System. Windows. Input. ICommand. • There are 2 delegate one for Can. Execute and Execute, which are constructor injected to Relay. Command. • In the View. Model we define the ICommand type for Add and Delete Item. • The implementation for Add. Employee. Method and Delete. Employee. Method are added in View. Model. This could also be in separate class if further segregation of commands. Demo: 5 are

COMMAND COMMUNICATION 3 4 • Relay. Command class is defined with Action and Predicate.

COMMAND COMMUNICATION 3 4 • Relay. Command class is defined with Action and Predicate. Action which encapsulates a method that has a single parameter and does not return a value. Predicate represents the method that defines a set of criteria and determines whether the specified object meets those criteria. • Add a new Selectedemp so that the user can delete the Selected Item from List. Box. • In the XAML, bind the Selectedemp as Selected Item in List. Box <List. Box Items. Source = "{Binding empl. Collection}" Selected. Item="{Binding Selected. Emp}"/> Demo: 5

COMMAND COMMUNICATION 5 • When the code is compiled and executed, the Delete button

COMMAND COMMUNICATION 5 • When the code is compiled and executed, the Delete button is not enabled as selectedemp is null. • When the item is selected the Delete button is enabled. • For demo purpose, the Add Random Employee is always enabled, again the pre-condition could also be added to enable and disable this button. 6 Demo: 5

DATA VALIDATIONS IN MODEL 1 • Validating the input to confirm it’s meets mandatory

DATA VALIDATIONS IN MODEL 1 • Validating the input to confirm it’s meets mandatory requirements. We talk about an example with usage of IData. Error. Info and Validates. On. Data. Errors to validate user input to textbox. • MVVM could be used to leverage such validations of user input. Since data model is defined in the Model, the data validations could be done through implementing System. Component. Model. IData. Error. Info interface in Model or View. Model. • Implementation of the IData. Error. Info is the evaluation of error of individual properties. This interface gives us two properties, those are Error and this. Error is a message indicating what is wrong with this object. This[String] gets the error message for the property with the given name. Demo: 7

DATA VALIDATIONS IN MODEL 2 • We bind the First. Name Property of the

DATA VALIDATIONS IN MODEL 2 • We bind the First. Name Property of the Employee class to the Text. Box and set Validates. On. Data. Errors = True on binding. When user enters empty or numeric value, the red border with message and tooltip is shown as error. • Here in the example we create an instance of the class under Resources with A value for First. Name, the same class instance is binded to Text. Box. • Set Validates. On. Data. Errors true, so that it includes Data. Error. Validation. Rule. The Error. Template is defined, so that control template is applied Demo: 7 on

DATA VALIDATIONS IN MODEL 3 • So with validation added, when the program is

DATA VALIDATIONS IN MODEL 3 • So with validation added, when the program is run. We get Invalid message and tooltip, when no values are provided in Textbox.

DEPENDENCY INJECTION • Decoupling between View. Model and Services. Employee Services and operations could

DEPENDENCY INJECTION • Decoupling between View. Model and Services. Employee Services and operations could further be defined as operations or services like – Get. Employees(), Get. Employee. By. Id(string Id), Get. Employee. Department(string Id), Update. Employee(Employee), etc. • We create a new Interface IEmployee. Service • Then a class Employee. Service. Operation 1 Implements interface on all operations concerning Employees. 2

DEPENDENCY INJECTION 3 • Interface type of IEmployee. Service is defined in the view.

DEPENDENCY INJECTION 3 • Interface type of IEmployee. Service is defined in the view. Model. • The instance of type IEmployee. Service is passed as parameter to constructor of View. Model. This is called Dependency Injection • Then this instance is used to call the 4 methods within instance. • During the Data Context setting , we initialize the View. Model by providing the Employee. Service. Operation Class instance.

THANK YOU

THANK YOU