Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy
Download
Report
Transcript Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy
Adam Calderon – C# MVP
Application Development Practice Lead
Interknowlogy
More info on InterKnowlogy:
www.InterKnowlogy.com
Contact Information
E-mail: [email protected]
Phone: 760-930-0075 x274
Blog: http://blogs.InterKnowlogy.com/AdamCalderon
About Adam Calderon
Microsoft MVP – C#
Microsoft UI Server Frameworks Advisory Council
Developer / Author / Speaker / Teacher
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
Connecting UI Elements
Binding to Business Classes
DataSources
Binding to Collections
Converting Data
Data Templates
Data Validation
Binding Components
Target Object
Target Property
Binding Source
Path
Target Property Must be a dependency property
OneWay
TwoWay
OneWayToSource
OneTime
Triggering supported by TwoWay or
OneWayToSource mode of binding
Dependency property or INotifyPropertyChanged
UpdateSourceTrigger property
LostFocus/PropertyChanged/Explicit
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}"/>
<TextBox Grid.Column="1" Grid.Row="1">
<TextBox.Text>
<Binding Path="StartDate" Mode="TwoWay”
UpdateSourceTrigger="LostFocus"
Converter="{StaticResource dataConverter}"/>
</TextBox.Text>
</TextBox>
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);
Connecting UI Elements
Connecting UI Elements
Binding to Business Classes
DataSources
Binding to Collections
Converting Data
Data Templates
Data Validation
Classes must have a default constructor
Properties must be public
Can’t bind to public members
TwoWay binding requires implementing
INotifiyPropertyChange interface
Contained in System.ComponentModel
Must implement PropertyChangedEventHandler
Must raise PropertyChange event when
properties get updated
UpdateSourceTrigger dictates when property is
updated from UI Element
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));
}
}
}
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
Binding to Classes
Connecting UI Elements
Binding to Business Classes
DataSources
Binding to Collections
Converting Data
Data Templates
Data Validation
Provide data to UI Elements
Work in conjunction with DataContext
Come in many flavors
Business Objects
ObjectDataProvider
XmlDataProvider
ADO.NET
Element Assignment
<Grid.DataContext>
<Binding Source="{StaticResource orderData}"/>
</Grid.DataContext>
Inherited by child elements
Child element usage
<TextBox Text="{Binding Path=FirstName}“ />
Instantiates object in XAML
Can be used for DataContext
ConstructorParameters property
MethodName property
MethodParameters property
<ObjectDataProvider x:Key="myDataSource"
ObjectType="{x:Type src:Person}">
<ObjectDataProvider.ConstructorParameters>
<system:String>Joe</system:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
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
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
Data Sources
Connecting UI Elements
Binding to Business Classes Data Sources
DataSources
Binding to Collections
Converting Data
Data Templates
Data Validation
Must implement IEnumerable
Need to implement INotifyCollectionChange to
support TwoWay binding
Each object inside collection must support
INotifyPropertyChange
Support IEnumerable
Built-In Support for INotifyCollectionChange
Standard Collection members
Similar in concept to DataView
Works over your data like DataView
Filtering
Sorting
Grouping
Current Record Pointer (CurrencyManager)
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
Determines the sort order of a collection
Can contain many sorts
SortDescription structure properties
PropertyName
SortDirection
<CollectionViewSource Source="{StaticResource places}" x:Key="cvs">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="CityName"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
MyCollectionViewSource.SortDescriptions.add(new
SortDescription(“CityName”,ListSortDirection.Ascending);
Determines the grouping of a collection
Creates groups based on PropertyName
Can contain many entries
PropertyGroupDescription properties
PropertyName, Converter, StringComparison
<CollectionViewSource Source="{StaticResource places}" x:Key="cvs">
<CollectionViewSource.GroupDescriptions>
<dat:PropertyGroupDescription PropertyName="State"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
MyCollectionViewSource.GroupDescriptions.add(new
PropertyGroupDescription(“State);
Binding to Collections
Connecting UI Elements
Binding to Business Classes
DataSources
Binding to Collections
Converting Data
Data Templates
Data Validation
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
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
IValueConverter
Convert
ConvertBack
IMultiValueConverter
▪ Convert
▪ ConvertBack
//[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;
}
}
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;
}
}
Converting Data
Connecting UI Elements
Binding to Business Classes
DataSources
Binding to Collections
Converting Data
Data Templates
Data Validation
Makes it easy to put content with data
Easy to define visual styles for data
Reusable and modifiable
Single Binding
Repeated Binding (ItemTemplate)
Typed Based
Heterogeneous Collections
Template Selection
Data Templates
Connecting UI Elements
Binding to Business Classes
DataSources
Binding to Collections
Converting Data
Data Templates
Data Validation
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
Called before any converter is called
Applies to 2-Way and OneWayToSource binding
modes only
UpdateSourceTrigger dependent
LostFocus
PropertyChanged
Explicit
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; }
}
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
Data Validation
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
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
MSDN® Links
Microsoft Windows® Vista™ development center:
http://msdn2.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.netfx3.com/
More info on InterKnowlogy:
www.InterKnowlogy.com
Contact Information
E-mail: [email protected]
Phone: 760-930-0075 x274
Blog: http://blogs.InterKnowlogy.com/AdamCalderon
About Adam Calderon
Microsoft MVP – C#
Microsoft UI Server Frameworks Advisory Council
Developer / Author / Speaker / Teacher