SlideShare une entreprise Scribd logo
1  sur  27
Model
View (XAML)
ViewModel
Design/Development Separation
Code Reuse
Multiple Views On the Same
Logic
View-Logic Testability
Model
View (XAML)
ViewModel
Model
ViewModel
View
ViewModel - C#
View - XAML
View (XAML)
ViewModel
DataBinding
Binding engine gets info from the Binding
object:
Binding Target
(Property)
Binding Source
(DependecyProperty /
INotifyPropertyChanged)
Binding
Object
Data Updates
(one-way)
Data Updates
(two-way)
Data Updates
(one-way)
Data Updates
(two-way)
A DependencyProperty is a special type of
property
<TextBlock x:Name="DescriptionTextBlock" Margin="12,0,0,0" Text="{Binding Description} " />
Dependency Property Binding Markup ExtensionDependency Object
Converters - bind a target and a source that are
different types
<TextBlock x:Name="MyTextBlock" Visibility="{Binding IsVisibleBool, Converter={StaticResource
BoolToVisibilityConverter}}" />
<Image Source="{Binding VisualElement.BackgroundImage, Mode=OneTime}" />
OneTime
OneWay
TwoWay
More advanced property paths
Use the StringFormat property to format text
<Image Source="{Binding VisualElement.BackgroundImage, Mode=OneTime}" />
<TextBlock Text="{Binding Coupon.ExpirationDate, StringFormat=‘Expiration Date: {0:d}’}‚ />
ViewModel acts as a binding source
Loosely coupled to a View
public class ItemView Model : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set {
if (value != _name)
{
_name = value;
NotifyPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
OneWay or TwoWay binding must implement the
INotifyPropertyChanged interface
Two ways to bind collections of data:
ViewModel - C#
ICommand
DelegateCommand
RelayCommand
View XAML
Command=“{Binding MyCommand}”
View (XAML)
ViewModel
Commands
Expose a method like a property
Attach commands to buttons and menu items
View notifies the code that some action has
occurred
Implement the ICommand interface
<Button Content="Say Hello" Command="{Binding HelloWorldCommand}"></Button>
class HelloWorldCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
MessageBox.Show("Hello world!");
}
}
class MyView Model
{
private HelloWorldCommand myCommand = new
HelloWorldCommand();
public HelloWorldCommand HelloWorldCommand
{
get
{
return myCommand;
}
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
DataContext = _myView Model;
}
Reusable ICommand class
See Implementation At
http://aka.ms/B4BDelegate
public MyViewModel()
{
loadSomeDataCommand = new DelegateCommand(LoadDataAction);
}
private void LoadDataAction(object p)
{
// Load the data into the ObserverableCollection here
}
// Command Property
private ICommand loadSomeDataCommand;
public ICommand LoadDataCommand
{
get
{
return this.loadSomeDataCommand;
}
}
Portable Class Libraries
Windows 8 Windows Phone 8
Services
ViewModels (limited/abstract)
Models
Commands
Interfaces
Views (XAML)
App Lifecycle
Navigation
Views (XAML)
Converters
Shared ViewModels (Add as Link)
Storage, Alerts
View (XAML)
ViewModel
Model
Imagine Camp Algeria 2014 Build for both session2 mvvm

Contenu connexe

Tendances (11)

ATG Architecture
ATG ArchitectureATG Architecture
ATG Architecture
 
ATG Framework,Formhandlers,Pricing
ATG Framework,Formhandlers,PricingATG Framework,Formhandlers,Pricing
ATG Framework,Formhandlers,Pricing
 
Extjs presentation
Extjs presentationExtjs presentation
Extjs presentation
 
Lesson 05 Data Binding in WPF
Lesson 05 Data Binding in WPFLesson 05 Data Binding in WPF
Lesson 05 Data Binding in WPF
 
Lesson 09 Resources and Settings in WPF
Lesson 09 Resources and Settings in WPFLesson 09 Resources and Settings in WPF
Lesson 09 Resources and Settings in WPF
 
Lesson 06 Styles and Templates in WPF
Lesson 06 Styles and Templates in WPFLesson 06 Styles and Templates in WPF
Lesson 06 Styles and Templates in WPF
 
Metaandmete haldus - Jüri Harju
Metaandmete haldus -  Jüri HarjuMetaandmete haldus -  Jüri Harju
Metaandmete haldus - Jüri Harju
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
dvprimer-concepts
dvprimer-conceptsdvprimer-concepts
dvprimer-concepts
 
Configuring Data Binding part2 ABTO Software Lecture Korotchyn
Configuring Data Binding part2 ABTO Software Lecture KorotchynConfiguring Data Binding part2 ABTO Software Lecture Korotchyn
Configuring Data Binding part2 ABTO Software Lecture Korotchyn
 
Configuring Data Binding part1 ABTO Software Lecture Korotchyn
Configuring Data Binding part1 ABTO Software Lecture KorotchynConfiguring Data Binding part1 ABTO Software Lecture Korotchyn
Configuring Data Binding part1 ABTO Software Lecture Korotchyn
 

En vedette

Επαγγελματα
ΕπαγγελματαΕπαγγελματα
Επαγγελματα
koutris
 

En vedette (15)

Acton Accounting and Bookkeeping
Acton Accounting and BookkeepingActon Accounting and Bookkeeping
Acton Accounting and Bookkeeping
 
Peripartum ttt of infant of HIV +ve mother ( case report )
Peripartum ttt of infant of HIV +ve mother ( case report )Peripartum ttt of infant of HIV +ve mother ( case report )
Peripartum ttt of infant of HIV +ve mother ( case report )
 
Symfonia
SymfoniaSymfonia
Symfonia
 
Digipalvelun huolenpito?
Digipalvelun huolenpito?Digipalvelun huolenpito?
Digipalvelun huolenpito?
 
Regulamin 121212
Regulamin 121212Regulamin 121212
Regulamin 121212
 
Market Research Results
Market Research ResultsMarket Research Results
Market Research Results
 
การเขียนคำสั่งข้อมูลขั้นพื้นฐาน
การเขียนคำสั่งข้อมูลขั้นพื้นฐานการเขียนคำสั่งข้อมูลขั้นพื้นฐาน
การเขียนคำสั่งข้อมูลขั้นพื้นฐาน
 
Taksi tampere
Taksi tampereTaksi tampere
Taksi tampere
 
Ten-and-a-half thoughts about thought leadership from The Writer
Ten-and-a-half thoughts about thought leadership from The WriterTen-and-a-half thoughts about thought leadership from The Writer
Ten-and-a-half thoughts about thought leadership from The Writer
 
Banglalink-Din Bodoler chesta
Banglalink-Din Bodoler chestaBanglalink-Din Bodoler chesta
Banglalink-Din Bodoler chesta
 
Επαγγελματα
ΕπαγγελματαΕπαγγελματα
Επαγγελματα
 
Liikuntaa tunti päivässä.
Liikuntaa tunti päivässä.Liikuntaa tunti päivässä.
Liikuntaa tunti päivässä.
 
Los angeles
Los angelesLos angeles
Los angeles
 
Symfonia
SymfoniaSymfonia
Symfonia
 
Contrato
ContratoContrato
Contrato
 

Similaire à Imagine Camp Algeria 2014 Build for both session2 mvvm

Backbonejs
BackbonejsBackbonejs
Backbonejs
Sam Lee
 
Knockoutjs Part 4 Bindings Controlling text and appearance
Knockoutjs Part 4  Bindings  Controlling text and appearanceKnockoutjs Part 4  Bindings  Controlling text and appearance
Knockoutjs Part 4 Bindings Controlling text and appearance
Bhaumik Patel
 
Working with XML and JSON Serializing
Working with XML and JSON SerializingWorking with XML and JSON Serializing
Working with XML and JSON Serializing
ssusere19c741
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
Michał Orman
 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
MicrosoftFeed
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objects
Phúc Đỗ
 

Similaire à Imagine Camp Algeria 2014 Build for both session2 mvvm (20)

Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
Knockoutjs
KnockoutjsKnockoutjs
Knockoutjs
 
MVC Model Binding
MVC Model BindingMVC Model Binding
MVC Model Binding
 
Model binding
Model bindingModel binding
Model binding
 
Entity framework1
Entity framework1Entity framework1
Entity framework1
 
Backbonejs
BackbonejsBackbonejs
Backbonejs
 
XAML/C# to HTML5/JS
XAML/C#  to HTML5/JS XAML/C#  to HTML5/JS
XAML/C# to HTML5/JS
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Modelibra Software Family
Modelibra Software FamilyModelibra Software Family
Modelibra Software Family
 
MVVM & Data Binding Library
MVVM & Data Binding Library MVVM & Data Binding Library
MVVM & Data Binding Library
 
Knockoutjs Part 4 Bindings Controlling text and appearance
Knockoutjs Part 4  Bindings  Controlling text and appearanceKnockoutjs Part 4  Bindings  Controlling text and appearance
Knockoutjs Part 4 Bindings Controlling text and appearance
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
Working with XML and JSON Serializing
Working with XML and JSON SerializingWorking with XML and JSON Serializing
Working with XML and JSON Serializing
 
Knockout js session
Knockout js sessionKnockout js session
Knockout js session
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Stephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep DiveStephen Kennedy Silverlight 3 Deep Dive
Stephen Kennedy Silverlight 3 Deep Dive
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objects
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Imagine Camp Algeria 2014 Build for both session2 mvvm

  • 1.
  • 2. Model View (XAML) ViewModel Design/Development Separation Code Reuse Multiple Views On the Same Logic View-Logic Testability
  • 4. ViewModel - C# View - XAML View (XAML) ViewModel DataBinding
  • 5.
  • 6.
  • 7.
  • 8.
  • 9. Binding engine gets info from the Binding object: Binding Target (Property) Binding Source (DependecyProperty / INotifyPropertyChanged) Binding Object Data Updates (one-way) Data Updates (two-way) Data Updates (one-way) Data Updates (two-way)
  • 10.
  • 11. A DependencyProperty is a special type of property <TextBlock x:Name="DescriptionTextBlock" Margin="12,0,0,0" Text="{Binding Description} " /> Dependency Property Binding Markup ExtensionDependency Object
  • 12. Converters - bind a target and a source that are different types <TextBlock x:Name="MyTextBlock" Visibility="{Binding IsVisibleBool, Converter={StaticResource BoolToVisibilityConverter}}" />
  • 13. <Image Source="{Binding VisualElement.BackgroundImage, Mode=OneTime}" /> OneTime OneWay TwoWay
  • 14. More advanced property paths Use the StringFormat property to format text <Image Source="{Binding VisualElement.BackgroundImage, Mode=OneTime}" /> <TextBlock Text="{Binding Coupon.ExpirationDate, StringFormat=‘Expiration Date: {0:d}’}‚ />
  • 15.
  • 16. ViewModel acts as a binding source Loosely coupled to a View
  • 17. public class ItemView Model : INotifyPropertyChanged { private string _name; public string Name { get { return _name; } set { if (value != _name) { _name = value; NotifyPropertyChanged("Name"); } } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }
  • 18. OneWay or TwoWay binding must implement the INotifyPropertyChanged interface
  • 19. Two ways to bind collections of data:
  • 20. ViewModel - C# ICommand DelegateCommand RelayCommand View XAML Command=“{Binding MyCommand}” View (XAML) ViewModel Commands
  • 21. Expose a method like a property Attach commands to buttons and menu items View notifies the code that some action has occurred Implement the ICommand interface
  • 22. <Button Content="Say Hello" Command="{Binding HelloWorldCommand}"></Button> class HelloWorldCommand : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { MessageBox.Show("Hello world!"); } } class MyView Model { private HelloWorldCommand myCommand = new HelloWorldCommand(); public HelloWorldCommand HelloWorldCommand { get { return myCommand; } } } protected override void OnNavigatedTo(NavigationEventArgs e) { DataContext = _myView Model; }
  • 23. Reusable ICommand class See Implementation At http://aka.ms/B4BDelegate
  • 24. public MyViewModel() { loadSomeDataCommand = new DelegateCommand(LoadDataAction); } private void LoadDataAction(object p) { // Load the data into the ObserverableCollection here } // Command Property private ICommand loadSomeDataCommand; public ICommand LoadDataCommand { get { return this.loadSomeDataCommand; } }
  • 25.
  • 26. Portable Class Libraries Windows 8 Windows Phone 8 Services ViewModels (limited/abstract) Models Commands Interfaces Views (XAML) App Lifecycle Navigation Views (XAML) Converters Shared ViewModels (Add as Link) Storage, Alerts View (XAML) ViewModel Model

Notes de l'éditeur

  1. Commands – express the function that gets called when an event happens in a view
  2. INotifyPropertyChanged – just says that it has event structure to normalize the change event when a property is changed
  3. Commands – express the function that gets called when an event happens in a view
  4. Without data binding, you may end up with overly-large and hard-to-maintain code behind files for your views.The XAML data binding engine performs the work of observing for changes and then synchronizing data between the source and the target.
  5. The binding engine, a part of Windows Runtime, is hidden from the developer. The binding object supplies the engine with information about the binding so that it can perform its duties. The engine observes changes in the binding source and target and updates data appropriately. The developer can provide an optional value converter that converts data between the source format and target format (the two boxes in the diagram are the same converter).Note that the binding engine updates data depending on the binding mode – one time, one way, or two way.A data class that is suitable for being a binding source is known as a View Model.
  6. The binding statement does not say exactly which data object (binding source) is used to supply the value. It just states that if this element is bound to a data object with a property called Directions, the Text property will be synchronized with that property. The default binding mode is one-way, meaning that changes to the data model will change the view, but not vice versa. This can be done by setting the binding Mode to two-way.You define the actual object to use for data binding by setting the DataContext property. You can set DataContext on an individual element, or on a containing element, in which case it is inherited by all the contained controls. You can simply set DataContext on a Grid or on the whole Page. Note that this is usually done from code when the page is navigated to.
  7. The XAML code example shows a TextBlock with the Visibility property bound to IsVisibleBool (presumably defined in the DataContext object). Because the source and target types do not match, a class named BoolToVisibilityConverter is provided as a converter. That class should implement the IValueConverter interface and convert objects between bool and System.Windows.Visibility.We will see an example of a converter in the demo.
  8. If you only bind with the OneTimeMode, the source object does not need to implement INotifyPropertyChanged. The WP8 Runtime just queries the property once and does not need to track it afterwards. Do not needlessly use two-way binding when one-way or even one-time binding would work
  9. We will see examples of advanced property paths and the StringFormat property in the demo.Extra info aboutStringFormat:The formatting is applied after any convertersEscape special characters with a ‘\’
  10. XAML is one end of data binding, and the View Model is the other end. It essentially “presents” your app data to the view.A substantial part of your code should be in the View Model(s).
  11. In Windows 8,the [CallerMemberName] attribute is a new feature that lets you obtain the name of the method or property calling a method. It is used above to get the string name of the property being set (“Name” in this case), and can help avoid cluttering your code with constant strings to identify properties.
  12. The INotifyPropertyChanged interface lets an object participate as a source in a one-way or two-way data binding.The interface exposes a single event, PropertyChanged. Classes that implement this interface should fire the PropertyChanged event whenever a public setter is called. The name of the property is passed in the PropertyChangedEventArgs.
  13. The INotifyPropertyChanged interface lets an object participate as a source in a one-way or two-way data binding.The interface exposes a single event, PropertyChanged. Classes that implement this interface should fire the PropertyChanged event whenever a public setter is called. The name of the property is passed in the PropertyChangedEventArgs.
  14. INotifyPropertyChanged – just says that it has event structure to normalize the change event when a property is changed
  15. Commands can involve a lot of boilerplate code, but a library can be helpful with this.
  16. This is a very barebones implementation to get a command working, but it demonstrates the basic idea. The Command property of the Button is bound to a class that implements the ICommand interface.
  17. Commands can involve a lot of boilerplate code, but a library can be helpful with this.
  18. Commands can involve a lot of boilerplate code, but a library can be helpful with this.