SlideShare une entreprise Scribd logo
1  sur  21
Bruce Johnson, ObjectSharp Consulting
bjohnson@objectsharp.com
Data Bondage
The Basic Functionality


                                        .Title
                  .Text       Data                 Book Class
 TitleTextBox
                             Binding


                   Target               Source    Source Data
Target Element
                  Property             Property     Object
DataContext Matters
• A DataContext in WPF is similar to a DataSource in
  WinForms/ASP.NET
• Provides the basis for data binding

Book b = new Book() { Title=quot;The Firmquot;,
   Author=quot;John Grishamquot; };
this.DataContext = b;
Binding Expressions
• We saw a simple binding expression in our
  walkthrough
  Text=quot;{Binding Path=Title}quot;


• Binding expressions can be more complex
  Text=quot;{Binding Path=DateCreated.Month,
    Mode=OneWay}quot;
Data bindings can have different
                  modes
•   One way
•   Two way
•   One time
•   One way to source
•   Default
    – The characteristics of the target property
      determines the mode
Formatting strings during binding
• StringFormat property of Binding class
• Formats strings during transfer to target
  property
• Uses standard formatting strings, previously
  defined in .NET
<TextBlock Text=quot;{Binding Path=Price,
  StringFormat=Only {0:c} with purchase!}quot; />
Bindings have silent failure
• If a binding fails, no exception is generated
• The program’s output will note the binding
  failure
Collections as the DataContext
 It’s common to use a list of data items instead
  of a single one
 For example, a collection of books instead of a
  single book:
Private Books As New List(Of Book)
Private Sub Window1_Loaded(ByVal sender As Object, …
    Books.Add( _
      New Book(quot;Ender's Gamequot;, quot;Orson Scott Cardquot;))
    Books.Add( _
      New Book(quot;Old Man's Warquot;, quot;John Scalziquot;))
    Me.DataContext = Books
End Sub
Navigating with a ListBox
• Add an attribute to the XAML definition of the
  Listbox
<ListBox ItemsSource=quot;{Binding}quot;
    DisplayMemberPath=quot;Titlequot;
    IsSynchronizedWithCurrentItem=quot;Truequot; … >
• Listbox now navigates the Books collection

                   If your ListBox fails to navigate
                   the list, always check the
                   IsSynchronizedWithCurrentItem
                   property
Lots of possible data sources…
 XML data (XPath attribute instead of Path)
 ADO.NET Datasets, DataTables
 Resource lists defined in XAML

You can bind to any control property that is a
dependency property
     IF you can match data types
            But what if you can’t?
Value converters
• WPF has some built-in converters
  – For example, a string name of a color will be
    converted to a brush
• You can write your own converters
  – Convert one type to another
  – Reformat strings (if StringFormat not sufficient)
• Implement the IValueConverter interface
  – Convert method – data source property  WPF
    element property
  – ConvertBack method – WPF element property  data
    source property
Interesting applications
• Bind data field to visibility of element
  – Built-in BooleanToVisibilityConverter
• Bind month number to month name
• Bind graphic to data field
  – Have image vary based on value of data field
MultiBinding
• A MultiBinding instance binds several data
  fields in the source to one target property
• Collection of Binding instances gets the data
  fields
• Converter assembles and parses the fields
Validation during binding
• Binding can have a collection of validation rules
• Built-in rules handle exceptions and IDataErrorInfo
  – IDataErrorInfo support is new in FX3.5 SP1
  – Not available in Silverlight (even 3)
• You can write your own validation rules
  – Inherit from ValidationRule class
  – Override the Validate method
  – Return a ValidationResult object
     • ValidationResult has a static ValidResult when there's no error
Displaying validation errors
• By default, all you get is a red rectangle
   – Yes, I hate it too. It’s ugly.
   – It can be overridden with a control template
   – You’ll see this in the Control Templates section
• Validation class has a static GetErrors method to
  return errors on an element
• Validation class has an Errors attached property
  for an element
   – You can use some fancy binding on this property to
     display error messages in, e.g., tooltips
   – However, binding information must be present in
     every binding that is being validated
Another option – Error event
• Validation class has an attached event named Error
   – Set this event on some container that holds all of your
     fields




• Event args tells you if error is being added or
  removed
• Event args includes an Error object with
  ErrorContent property
Binding element-to-element
• Use ElementName property of binding instead
  of setting a DataContext
• Allows you to tie user interface elements
  together
• Example – zooming with Slider and TextBox
No-code zooming
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height=quot;*quot; />
    <RowDefinition Height=quot;8*quot; />
  </Grid.RowDefinitions>
  <StackPanel Name=quot;StackPanel1quot; Orientation=quot;Horizontalquot;>
     <Slider Height=quot;22quot; Name=quot;ZoomSliderquot; Width=quot;100quot;
             Minimum=quot;10quot; Maximum=quot;100quot; Value=quot;50quot; />
     <TextBox Height=quot;23quot; Name=quot;TextBox1quot;
           Text=quot;{Binding Path=Value, ElementName=ZoomSlider}quot;
           Width=quot;120quot; Margin=quot;5quot; />
  </StackPanel>
  <Ellipse Width=quot;{Binding Path=Value, ElementName=ZoomSlider}quot;
       Height=quot;{Binding Path=Value, ElementName=ZoomSlider}quot;
       Grid.Row=quot;1quot; Name=quot;Ellipse1quot; Stroke=quot;Blackquot; Fill=quot;Redquot;>
</Grid>
RelativeSource binding
• Allows properties of an element to be bound to
  other properties of that element
  Height=
    quot;{Binding RelativeSource={RelativeSource
    Self}, Path=Width}quot;
• Allows properties of an element to be bound to
  properties further up in the tree of elements
Questions?
• My contact information
  – EMail: bjohnson@objectsharp.com
  – Twitter: LACanuck
  – Blog: http://www.objectsharp.com/blogs/bruce
  – MSN: lacanadians@hotmail.com

Contenu connexe

Tendances

Xml 215-presentation
Xml 215-presentationXml 215-presentation
Xml 215-presentation
philipsinter
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
chomas kandar
 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Rails
rfischer20
 

Tendances (20)

Unit iv xml
Unit iv xmlUnit iv xml
Unit iv xml
 
DOM Quick Overview
DOM Quick OverviewDOM Quick Overview
DOM Quick Overview
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
Dom date and objects and event handling
Dom date and objects and event handlingDom date and objects and event handling
Dom date and objects and event handling
 
Xml 215-presentation
Xml 215-presentationXml 215-presentation
Xml 215-presentation
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
Xml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh malothXml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh maloth
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Using Webservice in iOS
Using Webservice  in iOS Using Webservice  in iOS
Using Webservice in iOS
 
Document object model
Document object modelDocument object model
Document object model
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web TechnologyInternet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
 
Unit iv xml dom
Unit iv xml domUnit iv xml dom
Unit iv xml dom
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
XML for beginners
XML for beginnersXML for beginners
XML for beginners
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
 
The Document Object Model
The Document Object ModelThe Document Object Model
The Document Object Model
 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Rails
 

Similaire à Data Bondage in WPF

NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
Samnang Chhun
 
Data binding in silverlight
Data binding in silverlightData binding in silverlight
Data binding in silverlight
msarangam
 
Data binding in silverlight
Data binding in silverlightData binding in silverlight
Data binding in silverlight
msarangam
 
Strategies for Design & Implementation of Domain-Specific Languages
Strategies for Design & Implementation of Domain-Specific LanguagesStrategies for Design & Implementation of Domain-Specific Languages
Strategies for Design & Implementation of Domain-Specific Languages
Eelco Visser
 

Similaire à Data Bondage in WPF (20)

Wpf Introduction
Wpf IntroductionWpf Introduction
Wpf Introduction
 
WPF and Databases
WPF and DatabasesWPF and Databases
WPF and Databases
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templating
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Itemscript, a specification for RESTful JSON integration
Itemscript, a specification for RESTful JSON integrationItemscript, a specification for RESTful JSON integration
Itemscript, a specification for RESTful JSON integration
 
Dev308
Dev308Dev308
Dev308
 
Java script
Java scriptJava script
Java script
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Ajax
AjaxAjax
Ajax
 
Javascript
JavascriptJavascript
Javascript
 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptx
 
J s-o-n-120219575328402-3
J s-o-n-120219575328402-3J s-o-n-120219575328402-3
J s-o-n-120219575328402-3
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Data binding in silverlight
Data binding in silverlightData binding in silverlight
Data binding in silverlight
 
Data binding in silverlight
Data binding in silverlightData binding in silverlight
Data binding in silverlight
 
Model-Driven Software Development - Strategies for Design & Implementation of...
Model-Driven Software Development - Strategies for Design & Implementation of...Model-Driven Software Development - Strategies for Design & Implementation of...
Model-Driven Software Development - Strategies for Design & Implementation of...
 
Strategies for Design & Implementation of Domain-Specific Languages
Strategies for Design & Implementation of Domain-Specific LanguagesStrategies for Design & Implementation of Domain-Specific Languages
Strategies for Design & Implementation of Domain-Specific Languages
 

Plus de Bruce Johnson

Plus de Bruce Johnson (8)

Introducing ASP.NET vNext
Introducing ASP.NET vNextIntroducing ASP.NET vNext
Introducing ASP.NET vNext
 
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQUnit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
 
Silverlight 4 Out Of Browser
Silverlight 4 Out Of BrowserSilverlight 4 Out Of Browser
Silverlight 4 Out Of Browser
 
Setting Your Data Free With OData
Setting Your Data Free With ODataSetting Your Data Free With OData
Setting Your Data Free With OData
 
Silverlight 4 and Expression Blend
Silverlight 4 and Expression BlendSilverlight 4 and Expression Blend
Silverlight 4 and Expression Blend
 
Overview of VS2010 and .NET 4.0
Overview of VS2010 and .NET 4.0Overview of VS2010 and .NET 4.0
Overview of VS2010 and .NET 4.0
 
Code Contracts In .Net
Code Contracts In .NetCode Contracts In .Net
Code Contracts In .Net
 
Whats New In Silverlight 3
Whats New In Silverlight 3Whats New In Silverlight 3
Whats New In Silverlight 3
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

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)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Data Bondage in WPF

  • 1. Bruce Johnson, ObjectSharp Consulting bjohnson@objectsharp.com
  • 3. The Basic Functionality .Title .Text Data Book Class TitleTextBox Binding Target Source Source Data Target Element Property Property Object
  • 4. DataContext Matters • A DataContext in WPF is similar to a DataSource in WinForms/ASP.NET • Provides the basis for data binding Book b = new Book() { Title=quot;The Firmquot;, Author=quot;John Grishamquot; }; this.DataContext = b;
  • 5. Binding Expressions • We saw a simple binding expression in our walkthrough Text=quot;{Binding Path=Title}quot; • Binding expressions can be more complex Text=quot;{Binding Path=DateCreated.Month, Mode=OneWay}quot;
  • 6. Data bindings can have different modes • One way • Two way • One time • One way to source • Default – The characteristics of the target property determines the mode
  • 7. Formatting strings during binding • StringFormat property of Binding class • Formats strings during transfer to target property • Uses standard formatting strings, previously defined in .NET <TextBlock Text=quot;{Binding Path=Price, StringFormat=Only {0:c} with purchase!}quot; />
  • 8. Bindings have silent failure • If a binding fails, no exception is generated • The program’s output will note the binding failure
  • 9. Collections as the DataContext  It’s common to use a list of data items instead of a single one  For example, a collection of books instead of a single book: Private Books As New List(Of Book) Private Sub Window1_Loaded(ByVal sender As Object, … Books.Add( _ New Book(quot;Ender's Gamequot;, quot;Orson Scott Cardquot;)) Books.Add( _ New Book(quot;Old Man's Warquot;, quot;John Scalziquot;)) Me.DataContext = Books End Sub
  • 10. Navigating with a ListBox • Add an attribute to the XAML definition of the Listbox <ListBox ItemsSource=quot;{Binding}quot; DisplayMemberPath=quot;Titlequot; IsSynchronizedWithCurrentItem=quot;Truequot; … > • Listbox now navigates the Books collection If your ListBox fails to navigate the list, always check the IsSynchronizedWithCurrentItem property
  • 11. Lots of possible data sources…  XML data (XPath attribute instead of Path)  ADO.NET Datasets, DataTables  Resource lists defined in XAML You can bind to any control property that is a dependency property IF you can match data types But what if you can’t?
  • 12. Value converters • WPF has some built-in converters – For example, a string name of a color will be converted to a brush • You can write your own converters – Convert one type to another – Reformat strings (if StringFormat not sufficient) • Implement the IValueConverter interface – Convert method – data source property  WPF element property – ConvertBack method – WPF element property  data source property
  • 13. Interesting applications • Bind data field to visibility of element – Built-in BooleanToVisibilityConverter • Bind month number to month name • Bind graphic to data field – Have image vary based on value of data field
  • 14. MultiBinding • A MultiBinding instance binds several data fields in the source to one target property • Collection of Binding instances gets the data fields • Converter assembles and parses the fields
  • 15. Validation during binding • Binding can have a collection of validation rules • Built-in rules handle exceptions and IDataErrorInfo – IDataErrorInfo support is new in FX3.5 SP1 – Not available in Silverlight (even 3) • You can write your own validation rules – Inherit from ValidationRule class – Override the Validate method – Return a ValidationResult object • ValidationResult has a static ValidResult when there's no error
  • 16. Displaying validation errors • By default, all you get is a red rectangle – Yes, I hate it too. It’s ugly. – It can be overridden with a control template – You’ll see this in the Control Templates section • Validation class has a static GetErrors method to return errors on an element • Validation class has an Errors attached property for an element – You can use some fancy binding on this property to display error messages in, e.g., tooltips – However, binding information must be present in every binding that is being validated
  • 17. Another option – Error event • Validation class has an attached event named Error – Set this event on some container that holds all of your fields • Event args tells you if error is being added or removed • Event args includes an Error object with ErrorContent property
  • 18. Binding element-to-element • Use ElementName property of binding instead of setting a DataContext • Allows you to tie user interface elements together • Example – zooming with Slider and TextBox
  • 19. No-code zooming <Grid> <Grid.RowDefinitions> <RowDefinition Height=quot;*quot; /> <RowDefinition Height=quot;8*quot; /> </Grid.RowDefinitions> <StackPanel Name=quot;StackPanel1quot; Orientation=quot;Horizontalquot;> <Slider Height=quot;22quot; Name=quot;ZoomSliderquot; Width=quot;100quot; Minimum=quot;10quot; Maximum=quot;100quot; Value=quot;50quot; /> <TextBox Height=quot;23quot; Name=quot;TextBox1quot; Text=quot;{Binding Path=Value, ElementName=ZoomSlider}quot; Width=quot;120quot; Margin=quot;5quot; /> </StackPanel> <Ellipse Width=quot;{Binding Path=Value, ElementName=ZoomSlider}quot; Height=quot;{Binding Path=Value, ElementName=ZoomSlider}quot; Grid.Row=quot;1quot; Name=quot;Ellipse1quot; Stroke=quot;Blackquot; Fill=quot;Redquot;> </Grid>
  • 20. RelativeSource binding • Allows properties of an element to be bound to other properties of that element Height= quot;{Binding RelativeSource={RelativeSource Self}, Path=Width}quot; • Allows properties of an element to be bound to properties further up in the tree of elements
  • 21. Questions? • My contact information – EMail: bjohnson@objectsharp.com – Twitter: LACanuck – Blog: http://www.objectsharp.com/blogs/bruce – MSN: lacanadians@hotmail.com