6. xaml & wpf - simple data-binding
DESCRIPTION
Data Binding in WPFTelerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2012/02/02/desktop-applications-csharp-wpfThe website and all video materials are in Bulgarian.Why We Need Data Binding?Simple BindingBinding a Control Property to Object Property Data ContextsBinding Class and its PropertiesBinding Control to Another ControlValue ConversionData ValidationBinding Path SyntaxUsing Relative SourcesUsing Update Source TriggersTRANSCRIPT
![Page 1: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/1.jpg)
Doncho Minkov
Telerik Software Academyacademy.telerik.com
Technical Trainerhttp://www.minkov.it
http://academy.telerik.com/
Data Binding in WPFData Binding, Binding Properties
![Page 2: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/2.jpg)
Table of Contents1. Why We Need Data Binding?
2. Simple Binding Binding a Control Property to
Object Property
3. Data Contexts
4. Binding Class and its Properties
5. Binding Control to Another Control
6. Value Conversion
7. Data Validation
8. Binding Path Syntax 2
![Page 3: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/3.jpg)
Table of Contents (2)
9. Using Relative Sources
10.Using Update Source Triggers
3
![Page 4: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/4.jpg)
Why We Need Data Binding?
![Page 5: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/5.jpg)
Why We Need Data Binding?
The purpose of most applications is: Displaying data to users Letting them edit that data
Developers' job is: Bring the data from a variety of
sources Expose the data in object,
hierarchical, or relational format With WPF’s data binding engine, you get more features with less code
5
![Page 6: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/6.jpg)
Why We Need Data Binding? (2)
Data binding is pulling information out of an object into another object or property Data binding means automatically
change a property when another property is changed
Many Windows applications are all about data
Data binding is a top concern in a user interface technologies like WPF or Silverlight
WPF and Silverlight0 provide very powerful data binding mechanisms
6
![Page 7: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/7.jpg)
Simple Binding
![Page 8: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/8.jpg)
Simple Binding Simple binding in WPF is the act of registering two properties with the data binding engine Letting the engine keep them
synchronized The synchronization and conversion are duties of the data binding engine in WPF
8
![Page 9: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/9.jpg)
Simple Binding (2) Binding a property to a data source property:
The shortcut binding syntax:
Binding between the Text property of the TextBox and an object called SomeName SomeName is a property of some
object to be named later
9
<TextBox ...> <TextBox.Text> <Binding Path="SomeName" /> </TextBox.Text></TextBox>
<TextBox Text="{Binding Path=SomeName}" />
![Page 10: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/10.jpg)
Data Contexts
![Page 11: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/11.jpg)
Data Contexts In WPF every FrameworkElement and every FrameworkContentElement has a DataContext property DataContext is an object used as
data source during the binding, addressed by binding Path
If you don’t specify a Source property WPF searches up the element tree
starting at the current element Looking for a DataContext property
that has been set11
![Page 12: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/12.jpg)
Data Contexts (2)
Two controls with a common logical parent can bind to the same data source
Providing a DataContext value for both of the text box controls 12
<!-- DataContextWindow.xaml --><Grid Name="GridMain"> … <TextBlock …>Name: </TextBlock> <TextBox Text="{Binding Path=Name}" … /> <TextBlock …>Age:</TextBlock> <TextBox Text="{Binding Path=Age}" … /> <Button Name="ButtonBirthday Content="Birthday!" … /></Grid>
![Page 13: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/13.jpg)
Data Contexts (3) Setting an object as a value of the grid’s DataContext property in the MainWindow constructor:
13
public partial class MainWindow : Window{ Person person = new Person("Tom", 11);
public MainWindow() { InitializeComponent(); GridMain.DataContext = person; } …}
![Page 14: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/14.jpg)
Data ContextsLive Demo
![Page 15: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/15.jpg)
Binding to Other Controls
![Page 16: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/16.jpg)
Binding to Other Controls
WPF provides binding of one element’s property to another element’s property
The button’s foreground brush will always follow foreground brush’s color of the age TextBox
16
<TextBox Name="ageTextBox" Foreground="Red" … /><Button … Foreground="{Binding ElementName=ageTextBox, Path=Foreground}" Content="Birthday" />
![Page 17: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/17.jpg)
Binding to Other ControlsLive Demo
![Page 18: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/18.jpg)
The Binding Class and Its Properties
![Page 19: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/19.jpg)
Binding Class A more full-featured binding example
This features are represent in Binding class Converter – convert values back and
forth from the data source ConverterParameter – parameter
passed to the IValueConverter methods during the conversion
19
<TextBox x:Name="TextBoxPerson" Foreground="{Binding Path=Age, Mode=OneWay, Source={StaticResource Tom}, Converter={StaticResource ageConverter}}" />
![Page 20: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/20.jpg)
Binding Class (2) More Binding class properties
ElementName – used when the source of the data is a UI element as well as the target
Mode – one of the BindingMode values TwoWay, OneWay, OneTime, OneWayToSource, or Default
Path – path to the data in the data source object
Source – a reference to the data source
20
![Page 21: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/21.jpg)
Binding Class (3) The binding target can be any WPF element Only allowed to bind to the
element’s dependency properties
The TextBox control is the binding target
Object that provides the data is the binding source
21
![Page 22: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/22.jpg)
Value Conversion
![Page 23: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/23.jpg)
Value Conversion In the previous example we might decide that anyone over age 25 is hot Should be marked in the UI as red
Binding to a non-Text property
Bound the age text box’s Text property to the Person object’s Age property
23
<TextBox Text="{Binding Path=Age}" Foreground="{Binding Path=Age, …}" … />
![Page 24: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/24.jpg)
Value Conversion (2) How to bind the Foreground property
of the text box to Age property on the Person object? The Age is of type Int32 and Foreground is of type Brush
Mapping from Int32 to Brush needs to be applied to the data binding from Age to Foreground
That’s the job of a ValueConverter
24
![Page 25: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/25.jpg)
Value Conversion (3) A value converter is an implementation of the IValueConverter interface Convert() – converting from the
source data to the target UI data ConvertBack() – convert back from
the UI data to the source data
25
![Page 26: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/26.jpg)
Value Conversion (4) Converter Int32 Brush
26
public class AgeToForegroundConverter : IValueConverter{ public object Convert(object value, Type targetType, …) { if (targetType != typeof(Brush)) { return null; } int age = int.Parse(value.ToString()); return (age > 25 ? Brushes.Red : Brushes.Black); } …}
![Page 27: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/27.jpg)
Value Conversion (4) Creating an instance of the converter class in the XAML:
27
<Window … xmlns:local="clr-namespace:WithBinding"> <Window.Resources> <local:Person x:Key="Tom" … /> <local:AgeToForegroundConverter x:Key="ageConverter"/> </Window.Resources> <Grid DataContext="{StaticResource Tom}"> … <TextBox Text="{Binding Path=Age}" Foreground="{Binding Path=Age, Converter={StaticResource ageConverter}}" … /> … <Button … Foreground="{Binding Path=Foreground, ElementName=ageTextBox}">Birthday</Button> </Grid></Window>
![Page 28: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/28.jpg)
Value ConversionLive Demo
![Page 29: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/29.jpg)
Data Validation
![Page 30: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/30.jpg)
Data Validation A validation validates a piece of data in the target when the binding occurs Derives from the base ValidationRule class
30
class EGNValidationRule : ValidationRule{ public override ValidationResult Validate( object value, CultureInfo cultureInfo) { if (Regex.IsMatch((string)value, "\A\d{10}\Z")) return new ValidationResult(true, null); else return new ValidationResult(false, "Invalid EGN"); }}
![Page 31: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/31.jpg)
Data Validation (2) When a validation result indicates invalid data, a ValidationError object is created Checking for errors:
Getting the error messages:
You can also listen to the ValidationError attached event
31
Validation.GetHasError(UIElement)
var errors = Validation.GetErrors(UIElement);string errorMsg = (string)errors[0].ErrorContent;
![Page 32: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/32.jpg)
Data Validation (3)
32
<Window x:Class="BindingValidation.MainWindow" … xmlns:local="clr-namespace:BindingValidation" /> … <TextBox Name="TextBoxEGN"> <TextBox.Text> <Binding Path="EGN"> <Binding.ValidationRules> <local:EGNValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> …</Window>
Enabling validation rules in the XAML:
![Page 33: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/33.jpg)
Data Validation (4)
33
<Window.Resources> <Style TargetType="{x:Type TextBox}"> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <WrapPanel> <Border BorderBrush="Red"> <AdornedElementPlaceholder/> </Border> <TextBlock Foreground="Red">!</TextBlock> </WrapPanel> </ControlTemplate> </Setter.Value> </Setter> </Style></Window.Resources>
Styling the UI controls containing an error:
![Page 34: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/34.jpg)
Binding Path Syntax
![Page 35: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/35.jpg)
Binding Path Syntax When you use Path=Something in a Binding statement, the Something can be in a number of formats Path=Property – bind to the property
of the current object (Path=Age) Path=(OwnerType.AttachedProperty)
– bind to an attached dependency property (Path=(Validation.HasError))
Path=Property.SubProperty – bind to a subproperty (Path=Name.Length)
35
![Page 36: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/36.jpg)
Binding Path Syntax (2)
Other formatsPath=Property[n] – bind to an indexer (Path=Names[0])
Path=Property/Property – master-detail binding (Path=Customers/Orders)
Path=(OwnerType.AttachedProperty)[n].SubProperty – bind to a mixture of properties, subproperties, and indexers Path=(Validation.Errors)[0].ErrorContent)
36
![Page 37: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/37.jpg)
Relative Sources
![Page 38: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/38.jpg)
Relative Sources Describes the location of the binding source relative to the position of the binding target
Relative sources Self FindAncestor TemplatedParent Previous 38
<TextBox ... ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}">
![Page 39: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/39.jpg)
Update Source Triggers
![Page 40: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/40.jpg)
Update Source Triggers In previous example validation doesn’t happen until the age text box loses focus
Validation can happen immediately when the control state changes Using the UpdateSourceTrigger
property on the Binding object
40
<TextBox …> <TextBox.Text> <Binding Path="Age" UpdateSourceTrigger="PropertyChanged"> … </Binding> </TextBox.Text></TextBox>
![Page 41: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/41.jpg)
Update Source Triggers UpdateSourceTrigger values
Default – updates "naturally" based on the target control
PropertyChanged – updates the source immediately
LostFocus – updates the source when focus changes
Explicit – when BindingExpression. UpdateSource() is explicitly called
41
![Page 42: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/42.jpg)
форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно
програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки
уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop
уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC
безплатен курс "Разработка на софтуер в cloud среда"
BG Coder - онлайн състезателна система - online judge
курсове и уроци по програмиране, книги – безплатно от Наков
безплатен курс "Качествен програмен код"
алго академия – състезателно програмиране, състезания
ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия
курс мобилни приложения с iPhone, Android, WP7, PhoneGap
free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно
?
? ? ??
?? ?
?
?
?
??
?
?
? ?
Questions?
?http://academy.telerik.com
Simple Data Binding
![Page 43: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/43.jpg)
Exercises
1. Write a program that show a simple window, it contains two controls a Slider and a TextBlock with a single line of text. If you pull the thumb in the slider to the right, the font size of the text is increased immediately. Add a label that shows the current font size. Use data binding.
2. Add to the previous exercise few buttons each of which applies a preset value to the slider. When you click the "Set to Large" button the code in Click event sets the value of the slider, which in turn forces a change to the font size of the text through data binding.
43
![Page 44: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/44.jpg)
Exercises (2)
3. Write a program that shows a simple window, which contains a TextBlock and setup the TextBlock to draw its text from a TextBox and its current foreground and background colors from separate lists of colors.
4. Create an application to enter person's name and age. Bind the person's age with a slider showing the range [1..100]. Add custom validation rules to make sure that person’s age is within a the range (derive from the ValidationRule class and override the Validate() method).
44
![Page 45: 6. XAML & WPF - Simple Data-Binding](https://reader033.vdocuments.site/reader033/viewer/2022061214/5498ed09b47959f21e8b4572/html5/thumbnails/45.jpg)
Free Trainings @ Telerik Academy
Desktop Applications with C# and WPF academy.telerik.com/
Telerik Software Academy academy.telerik.com
Telerik Academy @ Facebook facebook.com/TelerikAcademy
Telerik Software Academy Forums forums.academy.telerik.com