{"id":384,"date":"2008-06-05T00:00:00","date_gmt":"2008-06-05T00:00:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/data-and-silverlight-2-data-binding\/"},"modified":"2021-05-17T18:36:47","modified_gmt":"2021-05-17T18:36:47","slug":"data-and-silverlight-2-data-binding","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/data-and-silverlight-2-data-binding\/","title":{"rendered":"Data and Silverlight 2: Data Binding"},"content":{"rendered":"<div id=\"pretty\">\n<h1>Data and Silverlight 2: Dependency Properties and Binding Syntax <\/h1>\n<p>Unlike Silverlight 1, Silverlight 2 has controls, .NET CLR support and data binding features. &#160;This article is the first of a series that describes the basic elements of data binding with Silverlight 2. <\/p>\n<h2>Data binding<\/h2>\n<p>While binding can be established using a manual push and pull process, the data binding capabilities of XAML and Silverlight offer more power and flexibility with less runtime code. This provides a more robust data bound user-interface with fewer failure points than with manual binding. <\/p>\n<p>The process of Automated Data-Binding in Silverlight links a UI <b>FrameworkElement<\/b> to a data source entity and back. The data source entity contains the data that will flow to the <b>FrameworkElement<\/b> control for presentation. The data can also flow from the control in Silverlight back to the entity. For example, an entity may be bound to a series of controls, each of which is linked to a specific property on the entity, as shown in Figure 1.<\/p>\n<p>The entity is set to the <b>DataContext<\/b> for a control. This then allows that control, or any child control of that control, to be bound directly to the entity. There are many important players in this process that will be introduced in this article, including the <b>DataContext<\/b>, binding modes, and dependency properties on FrameworkElement controls. Each of these plays a critical role in customizing how the data binding process operates in a Silverlight application. <\/p>\n<p><img loading=\"lazy\" decoding=\"async\" height=\"386\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/513-image001.png\" width=\"520\" alt=\"513-image001.png\" \/><\/p>\n<p class=\"figure\"><b>Figure 1.<\/b> Data binding in Silverlight 2<\/p>\n<p>There are some basic rules to follow when you are setting up data binding in Silverlight. The first rule is that the target element of a data binding operation must be a <b>FrameworkElement<\/b>. The second rule says that the target property must be a Dependency Property. <\/p>\n<h2>Rule #1: FrameworkElement<\/h2>\n<p>The target of data binding must be a <b>FrameworkElement<\/b>. This many sound limiting but it is quite the opposite. The <b>FrameworkElement<\/b> has many subclasses that inherit from it. Figure 2 shows several controls that inherit from the <b>FrameworkElement<\/b>. The <b>FrameworkElement<\/b> extends the <b>UIElement<\/b> class and adds capabilities that allow it to control layout and support data binding. <\/p>\n<p>Any control that derives from <b>FrameworkElement<\/b> can be used for layout on a page or user control, and can be involved in data binding as a target. There are other classes that derive from some of the subclasses shown in Figure 2, such as <b>System.Windows.Controls.Textbox<\/b>, too. <\/p>\n<p>In data binding, both a data source and at least one target are required. The target can be a control or set of controls on a page (or within a user control). Basically, the data can travel in either direction between the source and the target. The sources of data are generally instances of objects such as a domain entity. The properties of the data source are referred to in the targets, so that each target control knows which property of the entity it should be bound to. <\/p>\n<p><img loading=\"lazy\" decoding=\"async\" height=\"213\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/513-Leavethisalonetoo.jpg\" width=\"291\" alt=\"513-Leavethisalonetoo.jpg\" \/><\/p>\n<p class=\"figure\"><b>Figure 2.<\/b> FrameworkElement Class Hierarchy<\/p>\n<h2>Rule #2: Dependency Properties<\/h2>\n<p>As mentioned previously, the second rule of data binding in Silverlight is that the target must be a Dependency Property. This might initially seem to be a restriction, especially since one of the first controls people think about when they think of data binding is the TextBox&#8217;s Text property. However if you take a look at the source code (using a tool like Lutz Roeder&#8217;s .NET Reflector) for the Text property of a TextBox you will see that it too is a Dependency Property. In fact most properties that you can think of are Dependency Properties, which is great, since that means you can use data binding with so many properties.<\/p>\n<p>Dependency Properties are data-bound properties whose value is determined at runtime. The purpose of dependency properties is to provide a way to determine the value of a property based on inputs including, but not limited to, user preferences, resources, styles, or data binding.&#160; An example of a Dependency Property can be seen in the XAML code snippet below by looking at the Fill property.<\/p>\n<pre class=\"lang:xhtml theme:github\">&lt;Rectangle Fill=\"#FFE5CECE\" Grid.Column=\"0\" Grid.Row=\"0\"  RadiusX=\"20\" RadiusY=\"20\" Opacity=\"0.8\" StrokeThickness=\"0\" \/&gt;\n<\/pre>\n<p>The Rectangle control&#8217;s Fill property is a Dependency Property that is set to a specific color, in this case. The Fill property&#8217;s value could be determined using a resource or by data binding to an object. This would allow the color of the rectangle to be determined at runtime.<\/p>\n<p>Dependency Properties are not declared as a standard .NET CLR type, but rather they are declared with a backing property of type <b>Dependency Property<\/b>. The code in Example 1 shows the public facing property <b>Fill<\/b> and its type Brush However you&#8217;ll see that its backing property is not <b>Brush<\/b> but rather the type <b>Dependency Property<\/b>. You can always identify a Dependency Property by looking at its backing property&#8217;s name. If the backing property name has the Property suffix then it is generally the backing property for a Dependency Property.<\/p>\n<p><b>Example 1<\/b>. DependencyProperty<\/p>\n<p><b>C# code<\/b><\/p>\n<pre class=\"lang:c# theme:vs2012\">public\nstatic readonly DependencyProperty FillProperty;public\nBrush Fill {\nget { return (Brush) this.GetValue(FillProperty); }\nset { base.SetValue(FillProperty, (DependencyObject) value); }\n}\n<\/pre>\n<p><b>VB Code<\/b><\/p>\n<pre class=\"lang:c# theme:vs2012\">Public Shared ReadOnly FillProperty As DependencyProperty Public\nProperty Fill() As Brush Get\nReturn CType(Me.GetValue(FillProperty), Brush)\nEnd Get\nSet(ByVal value As Brush)\nMyBase.SetValue(FillProperty, CType(value, DependencyObject))\nEnd Set\nEnd Property\n<\/pre>\n<p>Table 1 shows a quick reference of these terms applied to the code in Example 1<\/p>\n<table class=\"MsoNormalTable\" id=\"table1\">\n<thead>\n<tr>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellHeading\"><b>Term<\/b><\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellHeading\"><b>Description<\/b><\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellHeading\"><b>Explanation<\/b><\/p>\n<\/td>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">Dependency Property<\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">The property named Fill<\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">A property that is backed by a field of type Dependency Property<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">DependencyProperty <\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">The type of FillProperty<\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">A type that defines the backing field<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">Dependency Property Identifier<\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">The instance of the backing property,FillProperty . This is referred to in the CLR Wrapper code with the GetValue and SetValue methods.<\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">An instance of the Dependency Property<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">CLR Wrapper<\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">The setter and getter accessor code for the Fill property.<\/p>\n<\/td>\n<td valign=\"top\" align=\"left\">\n<p class=\"CellBody\">The getter and setter for the property<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><b>&#160;<\/b>A dependency property can also get its value through a data-binding operation. Instead of setting the value to a specific color or a Brush, the value can be set through data-binding. When using data-binding, the property&#8217;s value is determined at runtime from the binding to the data source.<\/p>\n<p>The following XAML example sets the Fill for a Rectangle using data-binding. The binding uses an inherited data context and an instance of an object data source (referred to as <b><i>MyShape<\/i><\/b>). The binding syntax and the <b>DataContext<\/b> will be explored later in this article.<\/p>\n<pre class=\"lang:xhtml theme:github\">&lt;Rectangle Fill=\"{Binding MyShape.FillColor}\"  Grid.Column=\"0\" Grid.Row=\"0\" \nRadiusX=\"20\" RadiusY=\"20\" Opacity=\"0.8\" StrokeThickness=\"0\" \/&gt;\n<\/pre>\n<p>Besides basic data binding, styles and templates are a huge beneficiary of using dependency properties. Controls that use styles are indicated through a <b>StaticResource<\/b> (defined in app.xaml or defined locally). The style resources are often set to a Dependency Property to achieve a more elegant appearance.<\/p>\n<p>Dependency Property values are determined using an order of precedence. For example a style resource may set the Background Dependency Property to <b><i>White<\/i><\/b> for a canvas control. However the Background color can be overridden in the control itself by setting the Background property to <b><i>Blue<\/i><\/b>. The order of precedence exists in order to ensure that the values are set in a consistent and predictable manner. The previous example of the Rectangle control shows that the locally-set property value has a higher precedence than a resource.<\/p>\n<p>When creating a binding, a Dependency Property of a <b>FrameworkElement<\/b> must be assigned to the binding. This is the target of the binding operation. The source of the binding can be assigned through the <b>DataContext<\/b> property of the UI element or any UI element that is a container for the bound UI element.<\/p>\n<h2>Silverlight Binding XAML Markup Extensions<\/h2>\n<p>One of the main pieces of functionality offered by the Dependency Property is its ability to be data bound. In XAML, the data binding works through a specific markup extension syntax. Alternatively, the binding can be established through .NET code. A set of XAML attributes exist in order to support the data binding features. A basic example of the usage of these extensions is shown in the pseudo-code examples below.<\/p>\n<pre class=\"lang:c# theme:vs2012\">&lt;someFrameworkElement&#160;property=\"{Binding}\" .http:\/\/www.simple-talk.com\/&gt;&lt;someFrameworkElement property=\"{Binding&#160;Path=pathvalue}\" .http:\/\/www.simple-talk.com\/&gt;&#160;&lt;someFrameworkElement&#160;&#160;&#160;&#160; property=\"{Binding&#160;oneOrMoreBindingProperties}\" .http:\/\/www.simple-talk.com\/&gt;&lt;someFrameworkElement&#160;property&#160;&#160;&#160; =\"{Binding&#160;Path=pathvalue,&#160;oneOrMoreBindingProperties}\" .http:\/\/www.simple-talk.com\/&gt;<\/pre>\n<p>The element must be a <b>FrameworkElement<\/b> (thus the name <b><i>someFrameworkElement<\/i><\/b>). The <b><i>property<\/i><\/b> would be replaced with the name of the property that will be the target of the binding. For example the element might be a TextBox and the property might be Text. To bind the value of the property to a source the binding markup extensions can be used. <\/p>\n<p>The Binding attribute indicates that the value for the Dependency Property will be derived from a data binding operation. The binding gets its source from the <b>DataContext<\/b> for the element or the <b>DataContext<\/b> that is inherited from the closest parent element. To bind an element to an object that is the <b>DataContext<\/b> (and not to a property of the object), all that is needed is the <b>Binding<\/b> attribute (see the first line of XAML from the previous example). For example, this is usually the case when binding an object that is a list to a ListBox.<\/p>\n<p>The second usage of the binding markup syntax is to specify a <b><i>pathvalue<\/i><\/b>. This can be the name of a property that exists on the bound object. For example, to bind a TextBox&#8217;s Text property to the <b>CompanyName<\/b> property of an object in the inherited<b> DataContext<\/b> the following code could be used:<\/p>\n<pre class=\"lang:c# theme:vs2012\">&lt;TextBox x:Name=\"tbCompany\" Text={Binding CompanyName}\"\/&gt;<\/pre>\n<h3>Binding Extension Properties<\/h3>\n<p>Additionally, there are a handful of other binding properties (referred to in the previous example as <b><i>oneOrMoreBindingProperties<\/i><\/b>) that can be set with the XAML binding extensions in Silverlight. These properties are:<\/p>\n<ul>\n<li>Converter  <\/li>\n<li>ConverterCulture  <\/li>\n<li>ConverterParameter  <\/li>\n<li>Mode  <\/li>\n<li>Source  <\/li>\n<li>Path  <\/li>\n<li>NotifyOnValidationError  <\/li>\n<li>ValidatesOnExceptions <\/li>\n<\/ul>\n<p>The Mode indicates the binding mode that specifies how the binding will operate. Valid values for the Mode property are <b>OneTime<\/b>, <b>OneWay<\/b> and <b>TwoWay<\/b>. An object reference can be set to the Source property. If the Source property is set the object reference will override the <b>DataContext<\/b> as the data source for this binding. All of these properties are optional. The default value for the Mode is OneWay while if the Source property is omitted the data source will defer to the <b>DataContext<\/b>.<\/p>\n<p>Keep in mind that a Dependency Property follows an order of precedence to determine its value. If a Dependency Property is bound and in code the property is set to a value explicitly, the binding is removed. For example the <b>tbCompany<\/b> TextBox in the previous example is bound to the <b>CompanyName<\/b> property of the <b>DataContext<\/b>. If the Text property of <b>tbCompany<\/b> is set to <i>Foo<\/i> in code, then the binding is removed.<\/p>\n<h1>DataContext<\/h1>\n<p>The <b>DataContext<\/b> refers to a source of data that can be bound to a target. The <b>DataContext<\/b> often is set to an instance of an entity. Once set, the <b>DataContext<\/b> can be bound to any controls that have access to it. It can be used to bind all controls within a container control to a single data source. This is useful when there are several controls that all use the same binding source. It could become repetitive to indicate the binding source for every control. Instead, the <b>DataContext<\/b> can be set for the container of the controls.<\/p>\n<p>Each <b>FrameworkElement<\/b> has a <b>DataContext<\/b>. This includes the instances of the <b>UserControl <\/b>class that the examples in this article have demonstrated, since the <b>UserControl<\/b> class inherits from the Control class which in turn inherits from the <b>FrameworkElement<\/b>&#160; class. This means that, on a single <b>UserControl<\/b>, there could be objects assigned to dozens of <b>DataContext<\/b> properties of various <b>FrameworkElement<\/b>&#160; controls. For example the <b>UserControl<\/b>, a layout control such as a Grid, and a series of interactive controls such as the TextBox, CheckBox and ListBox controls might all have their <b>DataContext<\/b> property set. <\/p>\n<p>To use the <b>DataContext<\/b>, the XAML must also be modified using the binding markup extension syntax. The newly modified XAML for the <b>UserControl<\/b> is shown in the code example below. This code is only the portion of the entire XAML file that shows only the elements where binding takes place.<\/p>\n<pre class=\"lang:c# theme:vs2012\">&lt;TextBox x:Name=\"tbFirstName\" Grid.Column=\"1\" Grid.Row=\"0\"  Margin=\"10,5,10,5\" HorizontalAlignment=\"Left\" Height=\"30\" \nWidth=\"240\" Style=\"{StaticResource textBoxStyle}\" \nText=\"{Binding FirstName}\"\/&gt;\n&lt;TextBox x:Name=\"tbLastName\" Grid.Column=\"1\" Grid.Row=\"1\" \nMargin=\"10,5,10,5\" HorizontalAlignment=\"Left\" Height=\"30\" \nWidth=\"240\" Style=\"{StaticResource textBoxStyle}\" \nText=\"{Binding LastName}\"\/&gt;\n&lt;TextBox x:Name=\"tbCompany\" Grid.Column=\"1\" Grid.Row=\"2\" \nMargin=\"10,5,10,5\" HorizontalAlignment=\"Left\" Height=\"30\" \nWidth=\"240\" Style=\"{StaticResource textBoxStyle}\" \nText=\"{Binding Company}\"\/&gt;\n<\/pre>\n<p>This XAML shows that the Text property of each TextBox is bound to a property of the data source. The data source is not listed anywhere in this XAML code. Therefore it is inferred that the Binding will use the <b>DataContext<\/b> that is closest in the inheritance hierarchy to the Target. If the TextBox itself has its <b>DataContext<\/b> property set, it will use the object from its own <b>DataContext<\/b>. <\/p>\n<p class=\"ExampleTitle\"><b>Example 2.<\/b> <b>DataContext<\/b> Binding<\/p>\n<p class=\"ExampleTitle\"><b>C# <\/b><\/p>\n<pre class=\"lang:c# theme:vs2012\">private void DataContextBinding_Loaded(object sender, RoutedEventArgs e)  {\nperson = new Person { FirstName = \"Ella\", \nLastName = \"Johnson\", Company = \"Hoo Company\" };\nthis.DataContext = person;\n}\n<\/pre>\n<p class=\"ExampleTitle\"><b>VB Code<\/b><\/p>\n<pre class=\"lang:c# theme:vs2012\">Private Sub DataContextBinding_Loaded(ByVal sender As Object, _  ByVal e As RoutedEventArgs)\nperson = New Person With {.FirstName = \"Ella\", _\n.LastName = \"Johnson\", .Company = \"Hoo Company\"}\nMe.DataContext = person\nEnd\nSub<\/pre>\n<p>The code in Example 2 shows the event handler that will execute when the <b>UserControl<\/b> is loaded. First an instance of the Person class is created and initialized. Then the <b>DataContext<\/b> property (also a Dependency Property) of the <b>UserControl<\/b> is set to the person instance. This gives each TextBox&#8217;s Binding a valid <b>DataContext<\/b> to use as the data source. Figure 3 shows the result of the binding. The <b>DataContext<\/b> is set for a container control (the <b>UserControl<\/b> itself). <\/p>\n<p><img loading=\"lazy\" decoding=\"async\" height=\"191\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/513-Leavethisalonethree.jpg\" width=\"366\" alt=\"513-Leavethisalonethree.jpg\" \/><\/p>\n<\/div>\n<p class=\"figure\"><b>Figure 3.<\/b> DataContext Binding<\/p>\n<h2>Summary<\/h2>\n<p>Silverlight 2 offers a variety of data binding features that all stem from some basic concepts as discussed in this article. All instances of the <b>FrameworkElement<\/b> class support data binding as a target while all properties of <b>FrameworkElement<\/b>s that are dependency properties can be a target property of a data binding operation. The <b>DataContext<\/b> is a very powerful way to bind a source object to one or more elements are multiple levels in XAML. These are the fundamental tools to data binding with Silverlight 2.<\/p>\n<div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Silverlight 2 is far more versatile than Silverlight 1. It can handle data-sources with some subtlety. John Papa tackles the whole subject of data-binding with Silverlight. This article is a partial excerpt from John Papa&#8217;s upcoming book Data Access with Silverlight 2 by O&#8217;Reilly, due to be released in December 2008. &hellip;<\/p>\n","protected":false},"author":221825,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143538],"tags":[4143,4229,4178,4838,4868,4179],"coauthors":[],"class_list":["post-384","post","type-post","status-publish","format-standard","hentry","category-dotnet-development","tag-net","tag-net-framework","tag-bi","tag-silverlight","tag-silverlight-how-to-example-data-binding","tag-source-control"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/384","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/221825"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=384"}],"version-history":[{"count":6,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/384\/revisions"}],"predecessor-version":[{"id":91142,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/384\/revisions\/91142"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=384"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=384"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=384"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=384"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}