Bruce Johnson, ObjectSharp Consulting
bjohnson@objectsharp.com
Data Bondage
The Basic Functionality


                                        .Title
                  .Text       Data               ...
DataContext Matters
• A DataContext in WPF is similar to a DataSource in
  WinForms/ASP.NET
• Provides the basis for data ...
Binding Expressions
• We saw a simple binding expression in our
  walkthrough
  Text=quot;{Binding Path=Title}quot;


• Bi...
Data bindings can have different
                  modes
•   One way
•   Two way
•   One time
•   One way to source
•   De...
Formatting strings during binding
• StringFormat property of Binding class
• Formats strings during transfer to target
  p...
Bindings have silent failure
• If a binding fails, no exception is generated
• The program’s output will note the binding
...
Collections as the DataContext
 It’s common to use a list of data items instead
  of a single one
 For example, a collec...
Navigating with a ListBox
• Add an attribute to the XAML definition of the
  Listbox
<ListBox ItemsSource=quot;{Binding}qu...
Lots of possible data sources…
 XML data (XPath attribute instead of Path)
 ADO.NET Datasets, DataTables
 Resource list...
Value converters
• WPF has some built-in converters
  – For example, a string name of a color will be
    converted to a b...
Interesting applications
• Bind data field to visibility of element
  – Built-in BooleanToVisibilityConverter
• Bind month...
MultiBinding
• A MultiBinding instance binds several data
  fields in the source to one target property
• Collection of Bi...
Validation during binding
• Binding can have a collection of validation rules
• Built-in rules handle exceptions and IData...
Displaying validation errors
• By default, all you get is a red rectangle
   – Yes, I hate it too. It’s ugly.
   – It can ...
Another option – Error event
• Validation class has an attached event named Error
   – Set this event on some container th...
Binding element-to-element
• Use ElementName property of binding instead
  of setting a DataContext
• Allows you to tie us...
No-code zooming
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height=quot;*quot; />
    <RowDefinition Height=quot;8*q...
RelativeSource binding
• Allows properties of an element to be bound to
  other properties of that element
  Height=
    q...
Questions?
• My contact information
  – EMail: bjohnson@objectsharp.com
  – Twitter: LACanuck
  – Blog: http://www.objects...
Upcoming SlideShare
Loading in …5
×

Data Bondage in WPF

2,133 views

Published on

The "Data Bondage in WPF" presentation from the Toronto Code Camp 2009

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,133
On SlideShare
0
From Embeds
0
Number of Embeds
9
Actions
Shares
0
Downloads
35
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Data Bondage in WPF

  1. 1. Bruce Johnson, ObjectSharp Consulting bjohnson@objectsharp.com
  2. 2. Data Bondage
  3. 3. The Basic Functionality .Title .Text Data Book Class TitleTextBox Binding Target Source Source Data Target Element Property Property Object
  4. 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. 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. 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. 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. 8. Bindings have silent failure • If a binding fails, no exception is generated • The program’s output will note the binding failure
  9. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 21. Questions? • My contact information – EMail: bjohnson@objectsharp.com – Twitter: LACanuck – Blog: http://www.objectsharp.com/blogs/bruce – MSN: lacanadians@hotmail.com

×