SlideShare a Scribd company logo
Data Binding in WPF Data Binding, Binding Properties Doncho Minkov Telerik School Academy http://schoolacademy.telerik.com   Technical Trainer http://www.minkov.it
Table of Contents 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
Table of Contents (2) Value Conversion Data Validation Binding Path Syntax Using Relative Sources Using Update Source Triggers
Why We Need Data Binding?
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
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
Simple  B inding
Simple  B inding 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
Simple  B inding  (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 <TextBox ...> <TextBox.Text> <Binding Path=&quot;SomeName&quot; /> </TextBox.Text> </TextBox> <TextBox Text=&quot;{Binding Path=SomeName}&quot; />
Data Contexts
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
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 <!-- DataContextWindow.xaml --> <Grid Name=&quot;GridMain&quot;> … <TextBlock …>Name: </TextBlock> <TextBox Text=&quot;{Binding Path=Name}&quot; … /> <TextBlock …>Age:</TextBlock> <TextBox Text=&quot;{Binding Path=Age}&quot; … /> <Button Name=&quot;ButtonBirthday Content=&quot;Birthday!&quot; … /> </Grid>
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(&quot;Tom&quot;, 11);  public MainWindow() { InitializeComponent(); GridMain.DataContext = person; } … }
Data Contexts Live Demo
Binding to Other Controls
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 <TextBox Name=&quot;ageTextBox&quot; Foreground=&quot;Red&quot; … /> <Button … Foreground=&quot;{Binding ElementName=ageTextBox,  Path=Foreground}&quot; Content=&quot;Birthday&quot; />
Binding to Other Controls Live Demo
The  Binding  Class and Its Properties
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 <TextBox x:Name=&quot;TextBoxPerson&quot;  Foreground=&quot;{Binding Path=Age, Mode=OneWay, Source={StaticResource Tom}, Converter={StaticResource ageConverter}}&quot; />
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
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
Value Conversion
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 <TextBox Text=&quot;{Binding Path=Age}&quot; Foreground=&quot;{Binding Path=Age, …}&quot; … />
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
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
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); } … }
Value Conversion (4) Creating an instance of the converter class in the XAML: <Window … xmlns:local=&quot;clr-namespace:WithBinding&quot;> <Window.Resources> <local:Person x:Key=&quot;Tom&quot; … /> <local:AgeToForegroundConverter x:Key=&quot;ageConverter&quot;/> </Window.Resources> <Grid DataContext=&quot;{StaticResource Tom}&quot;> … <TextBox Text=&quot;{Binding Path=Age}&quot; Foreground=&quot;{Binding Path=Age, Converter={StaticResource ageConverter}}&quot; … /> … <Button … Foreground=&quot;{Binding Path=Foreground, ElementName=ageTextBox}&quot;>Birthday</Button> </Grid> </Window>
Value Conversion Live Demo
Data Validation
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, &quot;\A\d{10}\Z&quot;)) return new ValidationResult(true, null); else return new ValidationResult(false, &quot;Invalid EGN&quot;); } }
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 Validation.GetHasError(UIElement) var errors = Validation.GetErrors(UIElement); string errorMsg = (string)errors[0].ErrorContent;
Data Validation (3) <Window x:Class=&quot;BindingValidation.MainWindow&quot; … xmlns:local=&quot;clr-namespace:BindingValidation&quot; /> … <TextBox Name=&quot;TextBoxEGN&quot;> <TextBox.Text> <Binding Path=&quot;EGN&quot;> <Binding.ValidationRules> <local:EGNValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> … </Window> Enabling validation rules in the XAML:
Data Validation (4) <Window.Resources> <Style TargetType=&quot;{x:Type TextBox}&quot;> <Setter Property=&quot;Validation.ErrorTemplate&quot;> <Setter.Value> <ControlTemplate> <WrapPanel> <Border BorderBrush=&quot;Red&quot;> <AdornedElementPlaceholder/> </Border> <TextBlock Foreground=&quot;Red&quot;>!</TextBlock> </WrapPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> Styling the UI controls containing an error:
Binding Path Syntax
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 )
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].SubProperty  – bind to a mixture of properties,  subproperties , and indexers Path=(Validation.Errors)[0].ErrorContent)
R elative  S ources
R elative  S ources D escribes the location of the binding source relative to the position of the binding target Relative sources Self FindAncestor TemplatedParent Previous <TextBox ... ToolTip=&quot;{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}&quot;>
U pdate  S ource  T riggers
U pdate  S ource  T riggers 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=&quot;Age&quot;  UpdateSourceTrigger=&quot;PropertyChanged&quot;> … </Binding> </TextBox.Text> </TextBox>
U pdate  S ource  T riggers UpdateSourceTrigger  values Default  – updates &quot;naturally&quot; based on the target control PropertyChanged  – updates the source immediately LostFocus  –  updates the source when focus changes Explicit  – when  BindingExpression. UpdateSource ()  is explicitly called
Simple Data Binding Questions? http://academy.telerik.com
Exercises 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. Add to the previous exercise few buttons each of which applies a preset value to the slider. When you click the &quot;Set to Large&quot; 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.
Exercises (2) 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. Create an application to enter person's name and age. Bind the person's age with a slider showing the range [1..100]. Add c ustom validation rules  to make sure that person’s age is within a the range ( derive  from the  ValidationRule  class and override the  Validate()  method).
Ad

More Related Content

What's hot (20)

ADO.NET
ADO.NETADO.NET
ADO.NET
Wani Zahoor
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
Anekwong Yoddumnern
 
Ajax
AjaxAjax
Ajax
Yoga Raja
 
Ado .net
Ado .netAdo .net
Ado .net
Manish Singh
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
Ngeam Soly
 
For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
Snehal Harawande
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
Randy Connolly
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
Sisir Ghosh
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
michael.labriola
 
Ado.net
Ado.netAdo.net
Ado.net
dina1985vlr
 
Java script
Java scriptJava script
Java script
Yoga Raja
 
ADO.NET
ADO.NETADO.NET
ADO.NET
Farzad Wadia
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
Madhuri Kavade
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
rchakra
 
Data Binding
Data BindingData Binding
Data Binding
LAY Leangsros
 
For Beginners - Ado.net
For Beginners - Ado.netFor Beginners - Ado.net
For Beginners - Ado.net
Tarun Jain
 
AJAX
AJAXAJAX
AJAX
Gouthaman V
 
Chap14 ado.net
Chap14 ado.netChap14 ado.net
Chap14 ado.net
mentorrbuddy
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
prabhu rajendran
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
FaRid Adwa
 

Similar to Simple Data Binding (20)

Dev308
Dev308Dev308
Dev308
guest2130e
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
Tomas Petricek
 
Silverlight week5
Silverlight week5Silverlight week5
Silverlight week5
iedotnetug
 
Entity Framework v2 Best Practices
Entity Framework v2 Best PracticesEntity Framework v2 Best Practices
Entity Framework v2 Best Practices
Andri Yadi
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
Mahmoud Ouf
 
Silverlight 5 whats new overview
Silverlight 5 whats new overviewSilverlight 5 whats new overview
Silverlight 5 whats new overview
mdc11
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
Igor Moochnick
 
Data binding in silverlight
Data binding in silverlightData binding in silverlight
Data binding in silverlight
msarangam
 
Data binding in silverlight
Data binding in silverlightData binding in silverlight
Data binding in silverlight
msarangam
 
Wpf Introduction
Wpf IntroductionWpf Introduction
Wpf Introduction
Martha Rotter
 
Entity framework 4.0
Entity framework 4.0Entity framework 4.0
Entity framework 4.0
Abhishek Sur
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
Mahmoud Ouf
 
An Overview of Entity Framework
An Overview of Entity FrameworkAn Overview of Entity Framework
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008
Jonas Follesø
 
WPF & Silverlight UI
WPF & Silverlight UIWPF & Silverlight UI
WPF & Silverlight UI
Dave Allen
 
Flex3 data binding
Flex3 data bindingFlex3 data binding
Flex3 data binding
guestdf3003
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
Xhtml Part2
Xhtml Part2Xhtml Part2
Xhtml Part2
nleesite
 
Data Bondage in WPF
Data Bondage in WPFData Bondage in WPF
Data Bondage in WPF
Bruce Johnson
 
Winforms
WinformsWinforms
Winforms
Girmachew Tilahun
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
Tomas Petricek
 
Silverlight week5
Silverlight week5Silverlight week5
Silverlight week5
iedotnetug
 
Entity Framework v2 Best Practices
Entity Framework v2 Best PracticesEntity Framework v2 Best Practices
Entity Framework v2 Best Practices
Andri Yadi
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
Mahmoud Ouf
 
Silverlight 5 whats new overview
Silverlight 5 whats new overviewSilverlight 5 whats new overview
Silverlight 5 whats new overview
mdc11
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
Igor Moochnick
 
Data binding in silverlight
Data binding in silverlightData binding in silverlight
Data binding in silverlight
msarangam
 
Data binding in silverlight
Data binding in silverlightData binding in silverlight
Data binding in silverlight
msarangam
 
Entity framework 4.0
Entity framework 4.0Entity framework 4.0
Entity framework 4.0
Abhishek Sur
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008
Jonas Follesø
 
WPF & Silverlight UI
WPF & Silverlight UIWPF & Silverlight UI
WPF & Silverlight UI
Dave Allen
 
Flex3 data binding
Flex3 data bindingFlex3 data binding
Flex3 data binding
guestdf3003
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
Jignesh Aakoliya
 
Xhtml Part2
Xhtml Part2Xhtml Part2
Xhtml Part2
nleesite
 
Ad

More from Doncho Minkov (20)

Web design Tools
Web design ToolsWeb design Tools
Web design Tools
Doncho Minkov
 
HTML 5
HTML 5HTML 5
HTML 5
Doncho Minkov
 
HTML 5 Tables and Forms
HTML 5 Tables and FormsHTML 5 Tables and Forms
HTML 5 Tables and Forms
Doncho Minkov
 
CSS Overview
CSS OverviewCSS Overview
CSS Overview
Doncho Minkov
 
CSS Presentation
CSS PresentationCSS Presentation
CSS Presentation
Doncho Minkov
 
CSS Layout
CSS LayoutCSS Layout
CSS Layout
Doncho Minkov
 
CSS 3
CSS 3CSS 3
CSS 3
Doncho Minkov
 
Adobe Photoshop
Adobe PhotoshopAdobe Photoshop
Adobe Photoshop
Doncho Minkov
 
Slice and Dice
Slice and DiceSlice and Dice
Slice and Dice
Doncho Minkov
 
Introduction to XAML and WPF
Introduction to XAML and WPFIntroduction to XAML and WPF
Introduction to XAML and WPF
Doncho Minkov
 
WPF Layout Containers
WPF Layout ContainersWPF Layout Containers
WPF Layout Containers
Doncho Minkov
 
WPF Templating and Styling
WPF Templating and StylingWPF Templating and Styling
WPF Templating and Styling
Doncho Minkov
 
WPF Graphics and Animations
WPF Graphics and AnimationsWPF Graphics and Animations
WPF Graphics and Animations
Doncho Minkov
 
Model View ViewModel
Model View ViewModelModel View ViewModel
Model View ViewModel
Doncho Minkov
 
Introduction to Cross-platform Mobile Development Course
Introduction to Cross-platform Mobile Development CourseIntroduction to Cross-platform Mobile Development Course
Introduction to Cross-platform Mobile Development Course
Doncho Minkov
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
Doncho Minkov
 
Tables and Forms in HTML
Tables and Forms in HTMLTables and Forms in HTML
Tables and Forms in HTML
Doncho Minkov
 
HTML5
HTML5HTML5
HTML5
Doncho Minkov
 
CSS Part I
CSS Part ICSS Part I
CSS Part I
Doncho Minkov
 
Ad

Recently uploaded (20)

TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 

Simple Data Binding

  • 1. Data Binding in WPF Data Binding, Binding Properties Doncho Minkov Telerik School Academy http://schoolacademy.telerik.com Technical Trainer http://www.minkov.it
  • 2. Table of Contents 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
  • 3. Table of Contents (2) Value Conversion Data Validation Binding Path Syntax Using Relative Sources Using Update Source Triggers
  • 4. Why We Need Data Binding?
  • 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
  • 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
  • 7. Simple B inding
  • 8. Simple B inding 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
  • 9. Simple B inding (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 <TextBox ...> <TextBox.Text> <Binding Path=&quot;SomeName&quot; /> </TextBox.Text> </TextBox> <TextBox Text=&quot;{Binding Path=SomeName}&quot; />
  • 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
  • 12. 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 <!-- DataContextWindow.xaml --> <Grid Name=&quot;GridMain&quot;> … <TextBlock …>Name: </TextBlock> <TextBox Text=&quot;{Binding Path=Name}&quot; … /> <TextBlock …>Age:</TextBlock> <TextBox Text=&quot;{Binding Path=Age}&quot; … /> <Button Name=&quot;ButtonBirthday Content=&quot;Birthday!&quot; … /> </Grid>
  • 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(&quot;Tom&quot;, 11); public MainWindow() { InitializeComponent(); GridMain.DataContext = person; } … }
  • 15. Binding to Other Controls
  • 16. 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 <TextBox Name=&quot;ageTextBox&quot; Foreground=&quot;Red&quot; … /> <Button … Foreground=&quot;{Binding ElementName=ageTextBox, Path=Foreground}&quot; Content=&quot;Birthday&quot; />
  • 17. Binding to Other Controls Live Demo
  • 18. The Binding Class and Its Properties
  • 19. 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 <TextBox x:Name=&quot;TextBoxPerson&quot; Foreground=&quot;{Binding Path=Age, Mode=OneWay, Source={StaticResource Tom}, Converter={StaticResource ageConverter}}&quot; />
  • 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
  • 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
  • 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 Bound the age text box’s Text property to the Person object’s Age property <TextBox Text=&quot;{Binding Path=Age}&quot; Foreground=&quot;{Binding Path=Age, …}&quot; … />
  • 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
  • 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
  • 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); } … }
  • 27. Value Conversion (4) Creating an instance of the converter class in the XAML: <Window … xmlns:local=&quot;clr-namespace:WithBinding&quot;> <Window.Resources> <local:Person x:Key=&quot;Tom&quot; … /> <local:AgeToForegroundConverter x:Key=&quot;ageConverter&quot;/> </Window.Resources> <Grid DataContext=&quot;{StaticResource Tom}&quot;> … <TextBox Text=&quot;{Binding Path=Age}&quot; Foreground=&quot;{Binding Path=Age, Converter={StaticResource ageConverter}}&quot; … /> … <Button … Foreground=&quot;{Binding Path=Foreground, ElementName=ageTextBox}&quot;>Birthday</Button> </Grid> </Window>
  • 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, &quot;\A\d{10}\Z&quot;)) return new ValidationResult(true, null); else return new ValidationResult(false, &quot;Invalid EGN&quot;); } }
  • 31. 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 Validation.GetHasError(UIElement) var errors = Validation.GetErrors(UIElement); string errorMsg = (string)errors[0].ErrorContent;
  • 32. Data Validation (3) <Window x:Class=&quot;BindingValidation.MainWindow&quot; … xmlns:local=&quot;clr-namespace:BindingValidation&quot; /> … <TextBox Name=&quot;TextBoxEGN&quot;> <TextBox.Text> <Binding Path=&quot;EGN&quot;> <Binding.ValidationRules> <local:EGNValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> … </Window> Enabling validation rules in the XAML:
  • 33. Data Validation (4) <Window.Resources> <Style TargetType=&quot;{x:Type TextBox}&quot;> <Setter Property=&quot;Validation.ErrorTemplate&quot;> <Setter.Value> <ControlTemplate> <WrapPanel> <Border BorderBrush=&quot;Red&quot;> <AdornedElementPlaceholder/> </Border> <TextBlock Foreground=&quot;Red&quot;>!</TextBlock> </WrapPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> Styling the UI controls containing an error:
  • 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 )
  • 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].SubProperty – bind to a mixture of properties, subproperties , and indexers Path=(Validation.Errors)[0].ErrorContent)
  • 37. R elative S ources
  • 38. R elative S ources D escribes the location of the binding source relative to the position of the binding target Relative sources Self FindAncestor TemplatedParent Previous <TextBox ... ToolTip=&quot;{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}&quot;>
  • 39. U pdate S ource T riggers
  • 40. U pdate S ource T riggers 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=&quot;Age&quot; UpdateSourceTrigger=&quot;PropertyChanged&quot;> … </Binding> </TextBox.Text> </TextBox>
  • 41. U pdate S ource T riggers UpdateSourceTrigger values Default – updates &quot;naturally&quot; based on the target control PropertyChanged – updates the source immediately LostFocus – updates the source when focus changes Explicit – when BindingExpression. UpdateSource () is explicitly called
  • 42. Simple Data Binding Questions? http://academy.telerik.com
  • 43. Exercises 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. Add to the previous exercise few buttons each of which applies a preset value to the slider. When you click the &quot;Set to Large&quot; 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.
  • 44. Exercises (2) 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. Create an application to enter person's name and age. Bind the person's age with a slider showing the range [1..100]. Add c ustom validation rules to make sure that person’s age is within a the range ( derive from the ValidationRule class and override the Validate() method).

Editor's Notes

  • #2: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #3: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #4: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #5: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #8: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #11: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #15: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #16: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #18: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #19: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #23: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #29: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #30: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #35: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #38: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #40: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #44: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #45: * 02/25/12 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##