V 1.0 Programming III. Automatic notifications with data binding (…Changed, INofityPropertyChanged, ObservableCollection, DataTemplate) Data formatters.

Slides:



Advertisements
Similar presentations
MVVM Overview Frank Shoemaker MindCrafted Systems
Advertisements

Module 1: Creating an Application by Using Windows Presentation Foundation Overview of WPF Creating a Simple WPF Application Handling Events and Commands.
WPF Layer Cake C#, C++/CLI and C
Dinko Jakovljević Microsoft Student Partner | BambooLab
Or How I Learned to Stop Worrying and Love the Binding Bryan Anderson.
WinRT Apps
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Programming Based on Events
Real world Windows Phone development Igor
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
.NET Database Technologies: Introduction to WPF and Entity Framework DataBinding.
V 1.0 Programming III. XML XAML Data Binding I.. V 1.0ÓE-NIK, 2014 XML (w3schools.com) A hierarchical way of defining data XML declaration + elements.
V 1.0 Programming III. Creation of additional windows Routed events.
Target: dependency property Source: any public property CLR and WPF properties Target: dependency property Source: any public property CLR and WPF properties.
Last lecture data binding, binding object markup extension bind to any prop with INotifyPropertyChanged, target must be dep. prop. bind to obj... so no.
V 1.1 Programming III. GUI APIs WPF Hello World Important UI elements UI elements / content models UI elements / inheritance.
An Introduction to Silverlight Matt Harrington Developer Evangelist, Microsoft October 20, 2011.
Xamarin.Forms Hands On.
Data Binding to Controls Programming in C# Data Binding to Controls CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
V 1.1 Programming III. Important events, properties, methods of UI elements XAML basics.
V 1.0 Programming III. Comparison of GUI APIs WPF Hello World UI elements Content models Inheritance chains.
C# Events and WPF #W5. Horizontal Prototype WPF Designed for rapid user interface design Used for many devices: Windows Phone, Tablets, PCs,
Windows Presentation Foundation Adam Calderon Principal Engineer Interknowlogy LLC
Session 08: Architecture Controllers or Managers Graphical User Interface (GUI) FEN AK - IT Softwarekonstruktion.
Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy.
V 1.1 Programming III. Creating additional windows Event handling: preview/routed events.
V 1.0 Programming III. Automatic notifications (…Changed, INofityPropertyChanged, ObservableCollection ) Data formatters Data conversions Resources.
Object Oriented Software Development 9. Creating Graphical User Interfaces.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
1 Chapter Eleven Handling Events. 2 Objectives Learn about delegates How to create composed delegates How to handle events How to use the built-in EventHandler.
Windows Phone MVVM and Unit Testing Step by Step Andy Wigley Windows Phone Development MVP, Mobile Software Consultant APPA Mundi Ltd WPH208.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL Windows Presentation Foundation Ruwan Wijesinghe.
Svetlin Nakov Telerik Corporation
Module 7 Data Binding to Collections. Module Overview Binding to Collections of Objects Using Collection Views Create Master-Detail User Interfaces Using.
Windows Presentation Foundation (WPF). Introduction Separates appearance of user interface from behavior Appearance usually specified by XAML Behavior.
Session 16 Pinball Game Construction Kit:. Pinball Version 1 Replaced the fire button with a mouse event. Multiple balls can be in the air at once. –Uses.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
Observer design pattern A closer look at INotifyPropertyChanged, INotifyPropertyChanging and ObservableCollection Observer design pattern1.
V 1.0 Programming III. Converters Resources. V 1.0ÓE-NIK, 2014 Converters Data conversion: –Can be automatic! E.g.: SolidColorBrush  string, int  string.
개발자가 알아야할 Binding 강남 DataBinding 스타일 Windows 8 앱개발자라면 꼭 알아야할.
ControlTemplate and DataTemplate Doncho Minkov Telerik School Academy Technical Trainer
Windows 10 UWP MVVM In Depth
C# - FCL/Form & Control Validation John Kelleher.
Module 4 Taking Control of the User Interface. Module Overview Sharing Logical Resources in an Application Creating Consistent User Interfaces by Using.
3 private void equalsButton_Click( object sender, RoutedEventArgs e) { calculateResult(); }
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
CPSC 481 – Week #7 Sowmya Somanath
V 1.0 Programming III. XAML Data Binding I.. V 1.0ÓE-NIK, 2014 XAML namespaces Namespaces define the allowed tags and attributes The one without the prefix.
Model View ViewModel Architecture. MVVM Architecture components.
V 1.0 Programming III. Visual/FrameworkElement descendants.
V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events.
Windows 8 apps and the MVVM pattern SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN, October 16 th
Programming with MVVM Miguel A. Castro Architect -
Creating rich applications using Model View ViewModel David Ross
Part of the Microsoft.NET Framework 3.0 Tomer Shamam.NET Technologies Expert Sela Group
Data Binding, Binding Properties Doncho Minkov Telerik School Academy Technical Trainer
Adam Schultz MVVM and WPF. MVVM Model, View, ViewModel A software architecture designed to separate out User Interface design, Business Logic, and Data.
In Windows 8 Store Applications
State of the Art in Mobile Development - AndRES Käver, 2016
Real world Windows Phone development
INF230 Basics in C# Programming
Computing with C# and the .NET Framework
Ben Riga 02 | Basics of View Models Ben Riga
Jim Fawcett CSE775 – Distributed Objects Spring 2011
An introduction to MVVM using WPF NISCHAL S
Page Navigation and Data Binding in Windows Runtime Apps
CSE775 DO supporting slides for VRTS Client Demo
Events, Delegates, and Lambdas
Presentation transcript:

V 1.0 Programming III. Automatic notifications with data binding (…Changed, INofityPropertyChanged, ObservableCollection, DataTemplate) Data formatters

V 1.0ÓE-NIK, 2014 Automatic notifications with data binding For the data binding to work, the target has to be notified that the source property has changed –If the source objects are built-in classes or UI elements, then usually this is pre-implemented (e.g. Slider.Value  Label.Content) –We need no such mechanisms if the ViewModel class (the DataContext) does not change (from the code) after the data binding The UI element did in fact change the ViewModel, but we did not changed the Viewmodel from the code If we use our own classes as source objects, then the target UI element will not be notified if the source property changes! 2

V 1.0ÓE-NIK, 2014 Example Aim: the Person class will be our DataContext, the Label displays the name, and the button will change the name Data binding in the XAML: 3 public MainWindow() { InitializeComponent(); currentPerson = new Person("Piros Péter"); this.DataContext = currentPerson; }

V 1.0ÓE-NIK, 2014 Example The event handler for the button’s Click event: The console will display the new name… … but the UI will still show the old name! 4 private void Button_Click(object sender, RoutedEventArgs e) { currentPerson.Name = "Kék Péter"; Console.WriteLine(currentPerson.Name); }

V 1.0ÓE-NIK, 2014 Automatic notifications with data binding Methods: 1.Dependency properties always emit a notification when they change – if our properties are dependency properties, their changes will be reflected in the UI (not required) 2.Raise the …Changed event when the property changes (separate events for the different properties) 3.Implement the INotifyPropertyChanged interface and use the PropertyChanged event when any property changes (one event for the whole class) 5

V 1.0ÓE-NIK, 2014 Automatic notification – …Changed event When a property changes, the xxxChanged event should be fired(xxx = the name of the property) The subscription for the event (by the target object) is automatic 6 public event EventHandler NameChanged; public string Name { get { return name; } set { name = value; EventHandler nameChanged = NameChanged; if (nameChanged != null) nameChanged(this, EventArgs.Empty); }

V 1.0ÓE-NIK, 2014 INotifyPropertyChanged The source class should implement the INotifyPropertyChanged interface (System.ComponentModel) It only contains one event: –public event PropertyChangedEventHandler PropertyChanged; This event should be fired if a property changes; the second parameter should be the name of the property –string.Empty or null, if all properties has changed 7 public string Name { get { return name; } set { name = value; PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(“Name")); }

V 1.0ÓE-NIK, 2014 INotifyPropertyChanged Advantage: no need for several events Usually we use it for more than one properties: OnPropertyChanged() 8 private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } public string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); }

V 1.0ÓE-NIK, 2014 INotifyPropertyChanged OnPropertyChanged(), since.NET4.5 9 private void OnPropertyChanged([CallerMemberName] string propertyName="") { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } public string Name { get { return name; } set { name = value; OnPropertyChanged(); }

V 1.0ÓE-NIK, 2014 Notifications – problems with collections If the source property is a collection, then the OnPropertyChanged() will only raise the event if the whole collection is replaced This will not detect: –If we exchange an element inside the collection –Add()/Remove()/Insert()… –If we change a property of an element inside the collection 10 public List NewsletterSubscriptions { get { return newsletterSubscriptions; } set { hirlevelFeliratkozasok = value; OnPropertyChanged("NewsletterSubscriptions"); //??? }

V 1.0ÓE-NIK, 2014 Notifications – problems with collections 11 List newList = new List (); newList.Add(new NewsletterSubscription("education", true)); currentPerson.NewsletterSubscriptions = newList; //good currentPerson.NewsletterSubscriptions[0] = new NewsletterSubscription("education", true); //not good currentPerson.NewsletterSubscriptions.Add( new NewsletterSubscription("education", true)); //not good currentPerson.NewsletterSubscriptions[0].Aktiv = false; //not good

V 1.0ÓE-NIK, 2014 Notifications – ObservableCollection Can be used just like List –System.Collections.ObjectModel Will send a notification: –If we exchange an element inside the collection –Add()/Remove()/Insert() –NOT if we change a property of an element inside the collection Implements the INotifyCollectionChanged interface 12 private ObservableCollection newsletterSubscriptions; public ObservableCollection NewsletterSubscriptions { get { return newsletterSubscriptions; } set { newsletterSubscriptions = value; OnPropertyChanged("NewsletterSubscriptions"); //??? }

V 1.0ÓE-NIK, 2014 Állapotértesítés – ObservableCollection 13 ObservableCollection newList = new ObservableCollection (); newList.Add(new NewsletterSubscription("education", true)); currentPerson.NewsletterSubscriptions = newList; //good currentPerson.NewsletterSubscriptions[0] = new NewsletterSubscription("education", true); //good currentPerson.NewsletterSubscriptions.Add( new NewsletterSubscription("education", true)); //good currentPerson.NewsletterSubscriptions[0].Aktiv = false; //not good

V 1.0ÓE-NIK, 2014 Notifications – unsolved problems Bindings and contents of ToString() values will never refresh… –If possible, avoid its usage! –Instead: in the Content, use a layout manager, and then multiple controls to display the individual properties (= several individual data bindings) –If we need the same layout for multiple ContentControls, then DataTemplate (ContentTemplate – not this semester) –If we are listing the elements in a ListBox control, then DataTemplate (ItemTemplate) or self-made control (not this semester) 14

V 1.0ÓE-NIK, 2014 Notifications – unsolved problems Changes in the property of a property –We assign/bind the main property to the DataContext of a layout manager/Template and then we bind the sub- properties to the individual UI elements –Or complex path (e.g.: {Binding Animal.WillBite}) –Or very often: self-made control… Changes in the property of an element in a collection –Usually DataTemplate (ItemTemplate) or custom control… For every suitable solution: –We have to implement the INotifyPropertyChanged interface in all classes in the binding –We have to use ObservableCollection 15

V 1.0ÓE-NIK, 2014 Changes in the properties of a property The container window’s DataContext is a person instance: 16 class Person : INotifyPropertyChanged { … private Animal pet; public Animal Pet { get { return per; } set { pet = value; OnPropertyChanged("Pet"); }

V 1.0ÓE-NIK, 2014 Changes in the property of an element in a collection 17 class Person : INotifyPropertyChanged { … private ObservableCollection newsletterSubscriptions; public ObservableCollection NewsletterSubscriptions { get { return newsletterSubscriptions; } set { newsletterSubscriptions = value; OnPropertyChanged("NewsletterSubscriptions"); } } //+NewsletterSubscription also implements } //the INotifyPropertyChanged interface

V 1.0ÓE-NIK, 2014 Data Formatters Sometimes the source property is not displayed directly, without modifications Formatters: –Easiest: …StringFormat properties ContentControl: ContentStringFormat property, it can only be used if the Content is a string ItemsControl: ItemStringFormat propery, it can only be used if the items are displayed as strings With data binding, if the target property is string (e.g. TextBox.Text), then within the {Binding} we can use the StringFormat –Its usage is similar as the string.Format formatter strings (special rules may apply) 18

V 1.0ÓE-NIK, 2014 Exercise HW: the assembled pizza should be saved into a ListBox HW: functionality to use a file to save/load the assembled pizzas 19