Presentation is loading. Please wait.

Presentation is loading. Please wait.

An introduction to MVVM using WPF NISCHAL S

Similar presentations


Presentation on theme: "An introduction to MVVM using WPF NISCHAL S"— Presentation transcript:

1 An introduction to MVVM using WPF NISCHAL S
WPF with MVVM An introduction to MVVM using WPF NISCHAL S

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

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

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

5 Understanding mvvm View Model
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 ViewModel through binding collection to invoking method in ViewModel. When user interacts on the View, such a button click/item selection, then the code in ViewModel is executed. This is possible when control’s command is data bound to ICommand property of the ViewModel. The view references the view model through its DataContext 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 INotifyPropertyChanged and  and INotifyCollectionChanged interfaces. Models classes that represent collections of typically  ObservableCollection<T> class, provides an implementation of the INotifyCollectionChanged interface. Model may also support data validation and error reporting through the IDataErrorInfo (or INotifyDataErrorInfo) interfaces. The IDataErrorInfo and INotifyDataErrorInfo 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.

6 Understanding mvvm ViewModel
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.

7 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: OneWay- 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. TwoWay- 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. OneWayToSource- is the reverse of OneWay 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. OneWay 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. Default to most controls. TwoWay 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. Default to few controls like TextBox, CheckBox, etc. OneWayToSource is the reverse of OneWay 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. UpdateSourceTrigger Bindings that are TwoWay or OneWayToSource listen for changes in the target property and propagate them back to the source. Edit the text of a TextBox to change the underlying source value. - LostFocus (default for TextBox.Text) - PropertyChanged - Explicit - When the application calls UpdateSource for that control, submit button clicked

8 WPF Binding – Some INTRODUCTION
UpdateSourceTrigger: Bindings that are TwoWay or OneWayToSource listen for changes in the target property and propagate them back to the source. Edit the text of a TextBox to change the underlying source value. LostFocus (default for TextBox.Text) PropertyChanged Explicit - When the application calls UpdateSource for that control, submit button clicked In this example the TextBox is binded to properties of Employee class like FirstName, LastName and Department. OneWay 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. TwoWay 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. OneWayToSource is the reverse of OneWay 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. UpdateSourceTrigger Bindings that are TwoWay or OneWayToSource listen for changes in the target property and propagate them back to the source. Edit the text of a TextBox to change the underlying source value. - LostFocus (default for TextBox.Text) - PropertyChanged - Explicit - When the application calls UpdateSource for that control, submit button clicked

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

10 Connecting Model, View and ViewModel
3 4 Two ways to construct view: The View, contains the setting for DataContext, It is null from start and should be assigned to source of your binding, which is ViewModel. Construct view in XAML. Another Option is to set data source from code behind of user control. Construct view from code behind. One reason for constructing the view model in Code-behind instead of XAML is that the View model constructor takes parameters, but XAML parsing can only construct elements if defined in default constructor. Why Constructor: DataContext property is set in the constructor method of view, but you could also defer the construction until the Load event of the view fires. There's no default source for the DataContext property (it's simply null from the start), but since a DataContext is inherited down through the control hierarchy, you can set a DataContext for the Window itself and then use it throughout all of the child controls. DataContext = this; // if the code-behind itself contains the collection that will be binded to the UI. After the standard InitalizeComponent() call, we assign the "this" reference to the DataContext, which basically just tells the Window that we want itself to be the data context. 2Way binding: Change the text in the textbox and tab there is change in TextBlock, This is because the bindings of the TextBoxes are set to TwoWay and it updates the Model as well, and from the model again the TextBlock is updated. Demo:1

11 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. DataTemplate has a key templateDisplay, used by the List Control to set that particular template. This is explicit template, where in template key is used by the List Control. The global application resource dictionary is in the App.xaml file. In this file you can include several resource dictionaries as a Merged Dictionary.  Demo:2

12 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 ItemTemplate property from a listbox .Add a DataType property in our template definition and make sure to include the namespace for model. Here data template is applied to all employee data implicitly. To make this an implicit, remove the ItemTemplate property from a listbox .Add a DataType property in our template definition and make sure to include the namespace for model. This points to Employee data Type. Demo:3

13 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 and 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.” Other Behavioural pattern: -Chain of responsibility pattern: Command objects are handled or passed on to other objects by logic-containing processing objects -Iterator pattern: Iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation -Strategy pattern: Algorithms can be selected on the fly -Visitor pattern: A way to separate an algorithm from an object Demo:5 *GAMMA, E. (1995). Design patterns: elements of reusable object-oriented software. Reading, Mass, Addison-Wesley.

14 Command communication
2 1 Create a RelayCommand class and implement the methods of Interface System.Windows.Input.ICommand. There are 2 delegate one for CanExecute and Execute, which are constructor injected to RelayCommand. In the ViewModel we define the ICommand type for Add and Delete Item. The implementation for AddEmployeeMethod and DeleteEmployeeMethod are added in ViewModel. This could also be in separate class if further segregation of commands are needed. Other Behavioural pattern: -Chain of responsibility pattern: Command objects are handled or passed on to other objects by logic-containing processing objects -Iterator pattern: Iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation -Strategy pattern: Algorithms can be selected on the fly -Visitor pattern: A way to separate an algorithm from an object Demo:5

15 Command communication
3 4 RelayCommand 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 ListBox. In the XAML, bind the Selectedemp as Selected Item in ListBox <ListBox ItemsSource = "{Binding emplCollection}" SelectedItem="{Binding SelectedEmp}"/> Demo:5

16 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

17 Data validations in Model
1 Validating the input to confirm it’s meets mandatory requirements. We talk about an example with usage of IDataErrorInfo and ValidatesOnDataErrors 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.ComponentModel.IDataErrorInfo interface in Model or ViewModel. Implementation of the IDataErrorInfo 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. Validation that are supported by WPF data binding including − Throwing exceptions on a property is set. Implementing the IDataErrorInfo interface. Implementing INotifyDataErrorInfo. Use WPF validation rules. There is also Validation Rule: Provides a way to create a custom rule in order to check the validity of user input. public override ValidationResult Validate(object value, CultureInfo cultureInfo) Demo:7

18 Data validations in Model
2 We bind the FirstName Property of the Employee class to the TextBox and set ValidatesOnDataErrors = 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 FirstName, the same class instance is binded to TextBox. Set ValidatesOnDataErrors true, so that it includes DataErrorValidationRule. The ErrorTemplate is defined, so that control template is applied on error. Validation that are supported by WPF data binding including − -Throwing exceptions on a property is set. -Implementing the IDataErrorInfo interface. -Implementing INotifyDataErrorInfo. -Use WPF validation rules. There is also Validation Rule: Provides a way to create a custom rule in order to check the validity of user input. public override ValidationResult Validate(object value, CultureInfo cultureInfo) Demo:7

19 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. If an error is raised, the binding engine creates a ValidationError with the error and adds it to the Validation.Errors collection of the bound element. The lack of an error clears this validation feedback, unless another rule raises a validation issue.

20 Dependency injection Decoupling between ViewModel and Services. Employee Services and operations could further be defined as operations or services like – GetEmployees(), GetEmployeeById(string Id), GetEmployeeDepartment(string Id), UpdateEmployee(Employee), etc. We create a new Interface IEmployeeService Then a class EmployeeServiceOperation Implements interface on all operations concerning Employees. 1 2

21 Dependency injection 3 Interface type of IEmployeeService is defined in the viewModel. The instance of type IEmployeeService is passed as parameter to constructor of ViewModel. This is called Dependency Injection Then this instance is used to call the methods within instance. During the Data Context setting , we initialize the ViewModel by providing the EmployeeServiceOperation Class instance. 4

22 Thank YOU


Download ppt "An introduction to MVVM using WPF NISCHAL S"

Similar presentations


Ads by Google