6. XAML & WPF - Simple Data-Binding


Published on

Data Binding in WPF
Telerik Software Academy:
The website and all video materials are in Bulgarian.

Why We Need Data Binding?
Simple Binding
Binding a Control Property to Object Property
Data Contexts
Binding Class and its Properties
Binding Control to Another Control
Value Conversion
Data Validation
Binding Path Syntax
Using Relative Sources
Using Update Source Triggers

Published in: Technology, Business
1 Comment
  • Windows Presentation Foundation (WPF) data binding provides a simple and consistent way for applications to present and interact with data. Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

6. XAML & WPF - Simple Data-Binding

  1. 1. Data Binding in WPF Data Binding, Binding PropertiesDoncho MinkovTechnical Trainerhttp://www.minkov.itTelerik Software Academyacademy.telerik.com
  2. 2. Table of Contents1. Why We Need Data Binding?2. Simple Binding  Binding a Control Property to Object Property3. Data Contexts4. Binding Class and its Properties5. Binding Control to Another Control6. Value Conversion7. Data Validation8. Binding Path Syntax 2
  3. 3. Table of Contents (2)9. Using Relative Sources10. Using Update Source Triggers 3
  4. 4. Why We Need Data Binding?
  5. 5. 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
  6. 6. 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
  7. 7. Simple Binding
  8. 8. 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
  9. 9. Simple Binding (2) Binding a property to a data source property: <TextBox ...> <TextBox.Text> <Binding Path="SomeName" /> </TextBox.Text> </TextBox> The shortcut binding syntax: <TextBox Text="{Binding Path=SomeName}" /> 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
  10. 10. Data Contexts
  11. 11. 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 set 11
  12. 12. Data Contexts (2) Two controls with a common logical parent can bind to the same data source <!-- 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> Providinga DataContext value for both of the text box controls 12
  13. 13. Data Contexts (3) Setting an object as a value of the grid’s DataContext property in the MainWindow constructor: public partial class MainWindow : Window { Person person = new Person("Tom", 11); public MainWindow() { InitializeComponent(); GridMain.DataContext = person; } … } 13
  14. 14. Data Contexts Live Demo
  15. 15. Binding to Other Controls
  16. 16. Binding to Other Controls WPF provides binding of one element’s property to another element’s property <TextBox Name="ageTextBox" Foreground="Red" … /> <Button … Foreground="{Binding ElementName=ageTextBox, Path=Foreground}" Content="Birthday" /> The button’s foreground brush will always follow foreground brush’s color of the age TextBox 16
  17. 17. Binding to Other Controls Live Demo
  18. 18. The Binding Classand Its Properties
  19. 19. Binding Class A more full-featured binding example <TextBox x:Name="TextBoxPerson" Foreground="{Binding Path=Age, Mode=OneWay, Source={StaticResource Tom}, Converter={StaticResource ageConverter}}" /> 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
  20. 20. 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
  21. 21. 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
  22. 22. Value Conversion
  23. 23. 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 <TextBox Text="{Binding Path=Age}" Foreground="{Binding Path=Age, …}" … /> Bound the age text box’s Text property to the Person object’s Age property 23
  24. 24. 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
  25. 25. 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
  26. 26. Value Conversion (4) Converter Int32  Brush 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); } … } 26
  27. 27. Value Conversion (4) Creating an instance of the converter class in the XAML:<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> 27
  28. 28. Value Conversion Live Demo
  29. 29. Data Validation
  30. 30. Data Validation A validation validates a piece of data in the target when the binding occurs  Derives from the base ValidationRule class class EGNValidationRule : ValidationRule { public override ValidationResult Validate( object value, CultureInfo cultureInfo) { if (Regex.IsMatch((string)value, "Ad{10}Z")) return new ValidationResult(true, null); else return new ValidationResult(false, "Invalid EGN"); } } 30
  31. 31. Data Validation (2) When a validation result indicates invalid data, a ValidationError object is created  Checking for errors: Validation.GetHasError(UIElement)  Getting the error messages: var errors = Validation.GetErrors(UIElement); string errorMsg = (string)errors[0].ErrorContent; You can also listen to the ValidationError attached event 31
  32. 32. Data Validation (3) Enabling validation rules in the XAML: <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> 32
  33. 33. Data Validation (4) Styling the UI controls containing an error: <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> 33
  34. 34. Binding Path Syntax
  35. 35. 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
  36. 36. Binding Path Syntax (2) Other formats Path=Property[n] – bind to an indexer (Path=Names[0]) Path=Property/Property – master-detail binding (Path=Customers/Orders) Path=(OwnerType.AttachedProperty)[n].Su bProperty – bind to a mixture of properties, subproperties, and indexers  Path=(Validation.Errors)[0].ErrorContent) 36
  37. 37. Relative Sources
  38. 38. Relative Sources Describes the location of the binding source relative to the position of the binding target <TextBox ... ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"> Relative sources  Self  FindAncestor  TemplatedParent  Previous 38
  39. 39. Update Source Triggers
  40. 40. 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 <TextBox …> <TextBox.Text> <Binding Path="Age" UpdateSourceTrigger="PropertyChanged"> … </Binding> </TextBox.Text> </TextBox> 40
  41. 41. 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
  42. 42. Simple Data Binding курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  43. 43. Exercises1. 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
  44. 44. 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 persons name and age. Bind the persons 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
  45. 45. 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