Download presentation
Presentation is loading. Please wait.
Published byAndrew Phillips Modified over 9 years ago
1
Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy
2
More info on InterKnowlogy: www.InterKnowlogy.com www.InterKnowlogy.com Contact Information E-mail: adamc@InterKnowlogy.comadamc@InterKnowlogy.com Phone: 760-930-0075 x274 Blog: http://blogs.InterKnowlogy.com/AdamCalderonhttp://blogs.InterKnowlogy.com/AdamCalderon About Adam Calderon Microsoft MVP – C# Microsoft UI Server Frameworks Advisory Council Developer / Author / Speaker / Teacher
3
Binding data to UI Elements Binding to Business Classes Working with DataSources Binding to Collections Using Converters to convert data during Binding Using Data Templates to visualize data Using Validators to validate user input
4
Connecting UI Elements Binding to Business Classes DataSources Binding to Collections Converting Data Data Templates Data Validation
5
Binding Components Target Object Target Property Binding Source Path Target Property Must be a dependency property
6
OneWay TwoWay OneWayToSource OneTime
7
Triggering supported by TwoWay or OneWayToSource mode of binding Dependency property or INotifyPropertyChanged UpdateSourceTrigger property LostFocus/PropertyChanged/Explicit
8
Binding using XAML Will be the method of choice for tools like Visual Studio Easy to follow <TextBox Name="targetTextBox" Grid.Column="1" Grid.Row="1" Text="{Binding Path=Rent, Mode=OneWayToSource, UpdateSourceTrigger=LostFocus}"/> <Binding Path="StartDate" Mode="TwoWay” UpdateSourceTrigger="LostFocus" Converter="{StaticResource dataConverter}"/>
9
Binding using Code Good choice for dynamic situations Can be hard to follow in some cases MyData myDataObject = new MyData(DateTime.Now); Binding myBinding = new Binding("MyDataProperty"); myBinding.Source = myDataObject; myText.SetBinding(TextBlock.TextProperty, myBinding);
10
Connecting UI Elements
11
Connecting UI Elements Binding to Business Classes DataSources Binding to Collections Converting Data Data Templates Data Validation
12
Classes must have a default constructor Properties must be public Can’t bind to public members TwoWay binding requires implementing INotifiyPropertyChange interface
13
Contained in System.ComponentModel Must implement PropertyChangedEventHandler Must raise PropertyChange event when properties get updated UpdateSourceTrigger dictates when property is updated from UI Element
14
class DateTimeSample : INotifyPropertyChanged { public DateTimeSample(){} private DateTime startDate; public DateTime StartDate { get { return startDate; } set { startDate = value; OnPropertyChanged("StartDate"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); }
15
Add INotifiyPropertyChange 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
16
Binding to Classes
17
Connecting UI Elements Binding to Business Classes DataSources Binding to Collections Converting Data Data Templates Data Validation
18
Provide data to UI Elements Work in conjunction with DataContext Come in many flavors Business Objects ObjectDataProvider XmlDataProvider ADO.NET
19
Element Assignment Inherited by child elements Child element usage
20
Instantiates object in XAML Can be used for DataContext ConstructorParameters property MethodName property MethodParameters property <ObjectDataProvider x:Key="myDataSource" ObjectType="{x:Type src:Person}"> Joe
21
Instantiates object in XAML Can be used for DataContext 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 XmlDocument
22
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
23
Data Sources
24
Connecting UI Elements Binding to Business Classes Data Sources DataSources Binding to Collections Converting Data Data Templates Data Validation
25
Must implement IEnumerable Need to implement INotifyCollectionChange to support TwoWay binding Each object inside collection must support INotifyPropertyChange
26
Support IEnumerable Built-In Support for INotifyCollectionChange Standard Collection members
27
Similar in concept to DataView Works over your data like DataView Filtering Sorting Grouping Current Record Pointer (CurrencyManager)
28
Serves as a source for data on an element Provides clean separation of “views” of the same data Supports Sorting by SortDescriptions collection Supports Grouping by GroupDescriptions collection
29
Determines the sort order of a collection Can contain many sorts SortDescription structure properties PropertyName SortDirection MyCollectionViewSource.SortDescriptions.add(new SortDescription(“CityName”,ListSortDirection.Ascending);
30
Determines the grouping of a collection Creates groups based on PropertyName Can contain many entries PropertyGroupDescription properties PropertyName, Converter, StringComparison MyCollectionViewSource.GroupDescriptions.add(new PropertyGroupDescription(“State);
31
Binding to Collections
32
Connecting UI Elements Binding to Business Classes DataSources Binding to Collections Converting Data Data Templates Data Validation
33
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
34
Contained in the System.Windows.Controls namespace BooleanToVisibilityConverter Converts True/False to Visible, Hidden or Collapsed BorderGapMaskConverter Represents a converter that converts the dimensions of a GroupBox control into a VisualBrush MenuScrollingVisibilityConverter Data binding converter to handle the visibility of repeat buttons in scrolling menus
35
IValueConverter Convert ConvertBack IMultiValueConverter ▪ Convert ▪ ConvertBack
36
//[ValueConversion(source type, target type)] [ValueConversion(typeof(DateTime), typeof(String))] public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string returnValue = string.Empty;... return returnValue; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { DateTime resultDateTime;... return resultDateTime; }
37
public class NameConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { string name; switch ((string)parameter) { case "FormatLastFirst": name = values[1] + ", " + values[0]; break;... } return name; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { string[] splitValues = ((string)value).Split(' '); return splitValues; }
38
Converting Data
39
Connecting UI Elements Binding to Business Classes DataSources Binding to Collections Converting Data Data Templates Data Validation
40
Makes it easy to put content with data Easy to define visual styles for data Reusable and modifiable
41
Single Binding Repeated Binding (ItemTemplate) Typed Based Heterogeneous Collections Template Selection
42
Data Templates
43
Connecting UI Elements Binding to Business Classes DataSources Binding to Collections Converting Data Data Templates Data Validation
44
Need for validation logic Integrated Solution Based on a ValidationRule and can have many associated with element Use ErrorTemplate property and a ControlTemplate for visual representation
45
Called before any converter is called Applies to 2-Way and OneWayToSource binding modes only UpdateSourceTrigger dependent LostFocus PropertyChanged Explicit
46
Abstract Class Override Validate method Returns a ValidationResult class public abstract class ValidationRule { // Methods protected ValidationRule(); public abstract ValidationResult Validate(object value, CultureInfo cultureInfo); } public class ValidationResult { static ValidationResult(); public ValidationResult(bool isValid, object errorContent); public object ErrorContent { get; } public bool IsValid { get; } public static ValidationResult ValidResult { get; } }
47
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 ExceptionValidationRule Raise exception in property setter
48
Data Validation
49
Data Binding is powerful INotifyPropertyChange enables business objects to participate in TwoWay binding ObjectDataSource and XmlDataSource provide XAML based source instantiation CollectionView and CollectionViewSource make working with collections easy
50
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
51
MSDN ® Links Microsoft Windows ® Vista ™ development center: http://msdn2.microsoft.com/en- us/windowsvista/default.aspx http://msdn2.microsoft.com/en- us/windowsvista/default.aspx Microsoft.NET Framework 3.0 for developers: http://msdn.microsoft.com/winfx/ http://msdn.microsoft.com/winfx/ Other Links Microsoft.NET Framework: http://www.netfx3.com/http://www.netfx3.com/
53
More info on InterKnowlogy: www.InterKnowlogy.com www.InterKnowlogy.com Contact Information E-mail: adamc@InterKnowlogy.comadamc@InterKnowlogy.com Phone: 760-930-0075 x274 Blog: http://blogs.InterKnowlogy.com/AdamCalderonhttp://blogs.InterKnowlogy.com/AdamCalderon About Adam Calderon Microsoft MVP – C# Microsoft UI Server Frameworks Advisory Council Developer / Author / Speaker / Teacher
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.