An Introduction to Data Binding in Windows Presentation

An Introduction to Data Binding in Windows Presentation Foundation (WPF) Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy

Adam Calderon More info on Inter. Knowlogy: www. interknowlogy. com � Contact Information E-mail: adamc@Inter. Knowlogy. com Phone: 760 -930 -0075 x 274 Blog: http: //blogs. Inter. Knowlogy. com/Adam. Calderon � � About Adam Calderon Microsoft MVP – C# Microsoft UI Server Frameworks Advisory Council Developer / Author / Speaker / Teacher

What We Will Cover �Binding data to UI Elements �Binding to Business Classes �Working with Data. Sources �Binding to Collections �Using Converters to convert data during Binding �Using Data Templates to visualize data �Using Validators to validate user input

Agenda �Connecting UI Elements �Binding to Business Classes �Data. Sources �Binding to Collections �Converting Data �Data Templates �Data Validation

Data Binding Overview Data Binding Concepts �Binding Components Target Object Target Property Binding Source Path �Target Property Must be a dependency property

Data Binding Overview Binding Modes �One. Way �Two. Way �One. Way. To. Source �One. Time

Data Binding Overview What Triggers Updates �Triggering supported by Two. Way or One. Way. To. Source mode of binding �Dependency property or INotify. Property. Changed �Update. Source. Trigger property Lost. Focus/Property. Changed/Explicit

Data Binding Overview Data Binding Methods (1) �Binding using XAML Will be the method of choice for tools like Visual Studio Easy to follow <Text. Box Name="target. Text. Box" Grid. Column="1" Grid. Row="1" Text="{Binding Path=Rent, Mode=One. Way. To. Source, Update. Source. Trigger=Lost. Focus}"/> <Text. Box Grid. Column="1" Grid. Row="1"> <Text. Box. Text> <Binding Path="Start. Date" Mode="Two. Way” Update. Source. Trigger="Lost. Focus" Converter="{Static. Resource data. Converter}"/> </Text. Box. Text> </Text. Box>

Data Binding Overview Data Binding Methods (2) �Binding using Code Good choice for dynamic situations Can be hard to follow in some cases My. Data my. Data. Object = new My. Data(Date. Time. Now); Binding my. Binding = new Binding("My. Data. Property"); my. Binding. Source = my. Data. Object; my. Text. Set. Binding(Text. Block. Text. Property, my. Binding);

Demonstration 1 Connecting UI Elements

Agenda �Connecting UI Elements �Binding to Business Classes �Data. Sources �Binding to Collections �Converting Data �Data Templates �Data Validation

Binding to Business Classes Overview �Classes must have a default constructor �Properties must be public �Can’t bind to public members �Two. Way binding requires implementing INotifiy. Property. Change interface

Binding to Business Classes INotify. Property. Change �Contained in System. Component. Model �Must implement Property. Changed. Event. Handler �Must raise Property. Change event when properties get updated �Update. Source. Trigger dictates when property is updated from UI Element

Binding to Business Classes INotify. Property. Change Sample class Date. Time. Sample : INotify. Property. Changed { public Date. Time. Sample(){} private Date. Time start. Date; public Date. Time Start. Date { get { return start. Date; } set { start. Date = value; On. Property. Changed("Start. Date"); } } public event Property. Changed. Event. Handler Property. Changed; private void On. Property. Changed(String info) { if (Property. Changed != null) { Property. Changed(this, new Property. Changed. Event. Args(info)); } } }

Binding to Business Classes Best Practices �Add INotifiy. Property. Change interface to classes �Leave business logic inside of business class �Use Converters (see later) to work with impedance issues �Use Validators (see later) to handle logic that is not appropriate in business classes

Demonstration 2 Binding to Classes

Agenda �Connecting UI Elements �Binding to Business Classes �Data. Sources �Binding to Collections �Converting Data �Data Templates �Data Validation

Data Sources Overview �Provide data to UI Elements �Work in conjunction with Data. Context �Come in many flavors Business Objects Object. Data. Provider Xml. Data. Provider ADO. NET

Data Sources Data. Context �Element Assignment <Grid. Data. Context> <Binding Source="{Static. Resource order. Data}"/> </Grid. Data. Context> �Inherited by child elements �Child element usage <Text. Box Text="{Binding Path=First. Name}“ />

Data Sources Object. Data. Provider �Instantiates object in XAML �Can be used for Data. Context �Constructor. Parameters property �Method. Name property �Method. Parameters property <Object. Data. Provider x: Key="my. Data. Source" Object. Type="{x: Type src: Person}"> <Object. Data. Provider. Constructor. Parameters> <system: String>Joe</system: String> </Object. Data. Provider. Constructor. Parameters> </Object. Data. Provider>

Data Sources Xml. Data. Provider �Instantiates object in XAML �Can be used for Data. Context �Can use inline Xml inside the element itself �Source property can be used to point to a Uri �Document property can be set to an Xml. Document

Data Sources Things to Think About �Xml and ADO. NET data sources most of the time require additional overhead for validation logic �Use Validators (see later) and put validation logic in them for Xml and ADO. NET data sources to limit calling back to server

Demonstration 3 Data Sources

Agenda �Connecting UI Elements �Binding to Business Classes Data Sources �Data. Sources �Binding to Collections �Converting Data �Data Templates �Data Validation

Binding to Collections Overview �Must implement IEnumerable �Need to implement INotify. Collection. Change to support Two. Way binding �Each object inside collection must support INotify. Property. Change

Binding to Collections Observable. Collection<T> �Support IEnumerable �Built-In Support for INotify. Collection. Change �Standard Collection members

Binding to Collections Collection. View �Similar in concept to Data. View �Works over your data like Data. View �Filtering �Sorting �Grouping �Current Record Pointer (Currency. Manager)

Binding to Collections Collection. View. Source �Serves as a source for data on an element �Provides clean separation of “views” of the same data �Supports Sorting by Sort. Descriptions collection �Supports Grouping by Group. Descriptions collection

Binding to Collections Sort. Descriptions. Collection �Determines the sort order of a collection �Can contain many sorts �Sort. Description structure properties Property. Name Sort. Direction <Collection. View. Source="{Static. Resource places}" x: Key="cvs"> <Collection. View. Source. Sort. Descriptions> <scm: Sort. Description Property. Name="City. Name"/> </Collection. View. Source. Sort. Descriptions> </Collection. View. Source> My. Collection. View. Source. Sort. Descriptions. add(new Sort. Description(“City. Name”, List. Sort. Direction. Ascending);

Binding to Collections Group. Description. Collection �Determines the grouping of a collection �Creates groups based on Property. Name �Can contain many entries �Property. Group. Description properties Property. Name, Converter, String. Comparison <Collection. View. Source="{Static. Resource places}" x: Key="cvs"> <Collection. View. Source. Group. Descriptions> <dat: Property. Group. Description Property. Name="State"/> </Collection. View. Source. Group. Descriptions> </Collection. View. Source> My. Collection. View. Source. Group. Descriptions. add(new Property. Group. Description(“State);

Demonstration 4 Binding to Collections

Agenda �Connecting UI Elements �Binding to Business Classes �Data. Sources �Binding to Collections �Converting Data �Data Templates �Data Validation

Converting Data Overview �Used when data doesn’t match between bindings create a conversion class �When to use Culture changes needed Different View of data then native storage Incompatible data types between target and source

Converting Data Out-of-Box Converters �Contained in the System. Windows. Controls namespace �Boolean. To. Visibility. Converter Converts True/False to Visible, Hidden or Collapsed �Border. Gap. Mask. Converter Represents a converter that converts the dimensions of a Group. Box control into a Visual. Brush �Menu. Scrolling. Visibility. Converter Data binding converter to handle the visibility of repeat buttons in scrolling menus

Converting Data How this works �IValue. Converter Convert. Back �IMulti. Value. Converter ▪ Convert. Back
![Converting Data IValue. Converter Sample //[Value. Conversion(source type, target type)] [Value. Conversion(typeof(Date. Time), typeof(String))] Converting Data IValue. Converter Sample //[Value. Conversion(source type, target type)] [Value. Conversion(typeof(Date. Time), typeof(String))]](http://slidetodoc.com/presentation_image_h/99501fb30387ad129fac91754d6ad9b7/image-36.jpg)
Converting Data IValue. Converter Sample //[Value. Conversion(source type, target type)] [Value. Conversion(typeof(Date. Time), typeof(String))] public class Date. Converter : IValue. Converter { public object Convert(object value, Type target. Type, object parameter, System. Globalization. Culture. Info culture) { string return. Value = string. Empty; . . . return. Value; } public object Convert. Back(object value, Type target. Type, object parameter, System. Globalization. Culture. Info culture) { Date. Time result. Date. Time; . . . return result. Date. Time; } }

Converting Data IMulti. Value. Converter Sample public class Name. Converter : IMulti. Value. Converter { public object Convert(object[] values, Type target. Type, object parameter, Culture. Info culture) { string name; switch ((string)parameter) { case "Format. Last. First": name = values[1] + ", " + values[0]; break; . . . } return name; } public object[] Convert. Back(object value, Type[] target. Types, object parameter, Culture. Info culture) { string[] split. Values = ((string)value). Split(' '); return split. Values; } }

Demonstration 5 Converting Data

Agenda �Connecting UI Elements �Binding to Business Classes �Data. Sources �Binding to Collections �Converting Data �Data Templates �Data Validation

Data Templates Overview �Makes it easy to put content with data �Easy to define visual styles for data �Reusable and modifiable

Data Templates Template Scenarios �Single Binding �Repeated Binding (Item. Template) �Typed Based �Heterogeneous Collections �Template Selection

Demonstration 6 Data Templates

Agenda �Connecting UI Elements �Binding to Business Classes �Data. Sources �Binding to Collections �Converting Data �Data Templates �Data Validation

Data Validation Overview �Need for validation logic �Integrated Solution �Based on a Validation. Rule and can have many associated with element �Use Error. Template property and a Control. Template for visual representation

Data Validation Process �Called before any converter is called �Applies to 2 -Way and One. Way. To. Source binding modes only �Update. Source. Trigger dependent Lost. Focus Property. Changed Explicit

Data Validation. Rule �Abstract Class �Override Validate method �Returns a Validation. Result class public abstract class Validation. Rule { // Methods protected Validation. Rule(); public abstract Validation. Result Validate(object value, Culture. Info culture. Info); } public class Validation. Result { static Validation. Result(); public Validation. Result(bool is. Valid, object error. Content); public object Error. Content { get; } public bool Is. Valid { get; } public static Validation. Result Valid. Result { get; } }

Data Validation Best Practices �Create separate DLL for rules �Use as a wrapper to common business logic Apply same logic on front end as backend Eases code maintenance �If logic is in property setters Use the WPF validation rule Exception. Validation. Rule Raise exception in property setter

Demonstration 7 Data Validation

Session Summary (1) �Data Binding is powerful �INotify. Property. Change enables business objects to participate in Two. Way binding �Object. Data. Source and Xml. Data. Source provide XAML based source instantiation �Collection. View and Collection. View. Source make working with collections easy

Session Summary (2) �Converters provides conversion functionality during the binding processes �Data Templates provide a rich way to visualize data �Data Validation provides flexible way to validate user input during the binding process

For More Information �MSDN® Links Microsoft Windows® Vista™ development center: http: //msdn 2. microsoft. com/enus/windowsvista/default. aspx Microsoft. NET Framework 3. 0 for developers: http: //msdn. microsoft. com/winfx/ �Other Links Microsoft. NET Framework: http: //www. netfx 3. com/

Additional Resources

Adam Calderon More info on Inter. Knowlogy: www. interknowlogy. com � Contact Information E-mail: adamc@Inter. Knowlogy. com Phone: 760 -930 -0075 x 274 Blog: http: //blogs. Inter. Knowlogy. com/Adam. Calderon � � About Adam Calderon Microsoft MVP – C# Microsoft UI Server Frameworks Advisory Council Developer / Author / Speaker / Teacher
- Slides: 53