data bondage in wpf
DESCRIPTION
The "Data Bondage in WPF" presentation from the Toronto Code Camp 2009TRANSCRIPT
DATA BONDAGE IN WPF
Bruce Johnson, ObjectSharp [email protected]
The Basic Functionality
TitleTextBox Data Binding
Book Class.Text .Title
Target Element TargetProperty
Source DataObject
SourceProperty
• A DataContext in WPF is similar to a DataSource in WinForms/ASP.NET
• Provides the basis for data binding
Book b = new Book() { Title="The Firm", Author="John Grisham" };this.DataContext = b;
DataContext Matters
Binding Expressions• We saw a simple binding expression in our
walkthroughText="{Binding Path=Title}"
• Binding expressions can be more complexText="{Binding Path=DateCreated.Month, Mode=OneWay}"
• One way• Two way• One time• One way to source• Default– The characteristics of the target property
determines the mode
Data bindings can have different modes
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="{Binding Path=Price, StringFormat=Only {0:c} with purchase!}" />
Bindings have silent failure
• If a binding fails, no exception is generated• The program’s output will note the binding
failure
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("Ender's Game", "Orson Scott Card")) Books.Add( _ New Book("Old Man's War", "John Scalzi")) Me.DataContext = Books
End Sub
Collections as the DataContext
• Add an attribute to the XAML definition of the Listbox
<ListBox ItemsSource="{Binding}" DisplayMemberPath="Title" IsSynchronizedWithCurrentItem="True" … >
• Listbox now navigates the Books collection
Navigating with a ListBox
If your ListBox fails to navigate the list, always check the IsSynchronizedWithCurrentItem property
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
Lots of possible data sources…
But what if you can’t?
• 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
Value converters
• 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
Interesting applications
• 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
MultiBinding
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="*" /> <RowDefinition Height="8*" /> </Grid.RowDefinitions> <StackPanel Name="StackPanel1" Orientation="Horizontal"> <Slider Height="22" Name="ZoomSlider" Width="100" Minimum="10" Maximum="100" Value="50" /> <TextBox Height="23" Name="TextBox1" Text="{Binding Path=Value, ElementName=ZoomSlider}" Width="120" Margin="5" /> </StackPanel> <Ellipse Width="{Binding Path=Value, ElementName=ZoomSlider}" Height="{Binding Path=Value, ElementName=ZoomSlider}" Grid.Row="1" Name="Ellipse1" Stroke="Black" Fill="Red"></Grid>
RelativeSource binding• Allows properties of an element to be bound to
other properties of that elementHeight="{Binding RelativeSource={RelativeSource Self}, Path=Width}"
• Allows properties of an element to be bound to properties further up in the tree of elements
Questions?
• My contact information– EMail: [email protected]– Twitter: LACanuck– Blog: http://www.objectsharp.com/blogs/bruce– MSN: [email protected]