Data Binding is one of the most important services offered by WPF. Data Binding just means connecting the user interface to the information to be displayed. The data source can be properties data from the database, xml or other element property which includes the graphical elements as well.

Binding Targets

Data Binding has a Target and the Target has to be an element in the User Interface.  The syntax below can be used for the Data Binding.

 

WPF Binding Target

WPF Binding Target

Binding is the class that derives from the markup extension base class. And the various properties of the Binding object can be set. This binding object will be incharge of the Text property value of the object. The object that owns this Text property can be FrameworkElement. We can also bind to framework content elements. WPF also allows us to bind with certain types that are not framework elements but can be associated with them like the Brush object. So as long as Brush is a property of the Framework Element we can use it in binding. Binding is a framework service and Binding also takes into account context of the Visual Tree. The Target property has to be a dependency property. A dependency property is a property which is managed by the WPF property system and almost all properties of framework elements are dependency properties.

Binding Expressions

As far as the source of the binding is concerned any .NET object can be used as a source. We also need to specify what part of the source we are talking about. So the binding markup syntax lets us set that. So using the Path property of the Binding helps us specify which property of the source object is to be used as a binding and if want to bind to the entire object rather than a property of the object then we do not need to specify the Property. If we are binding with an XML then we need to bind to the XPath property to specify the element to bind to in the XML. Another important property in Binding is Mode which determines which way the binding will behave with the source.

 

The binding system of WPF defines the appropriate default modes for the various WPF elements. For Example it will default the mode to two way for a textbox and one way for textbock.

Bindings in Code

In xaml we use markup extension to define our bindings. In code we can set the binding directly by calling the SetBinding method of the FrameworkElement. We have passed the path as a constructor parameter.

 

WPF Binding in Code

WPF Binding in Code

Another way of setting the binding is by using the BindingOperations helper class. This is useful when we are not aware of the target type at the compile time.

Explicit Data Source for Binding

For a binding to work properly we need to define its source. In the example below we have explicitly specified the Source for the Binding in xaml. So we have specified the source as current thread and the path as CurrentCulture.

WPF Explicit Data Source Binding

WPF Explicit Data Source Binding

 

But you should know that this is not how usually the Binding is done in WPF.

Explicit Data Source as Resource

This is somehow close to the way we usually do the data binding. We have a source object placed in the Resources section and multiple objects are using this source object. The Resources object is a dictionary in which we can put useful objects. And then we have bound this source objects to multiple textblocks. One of them does not specify a path so the textblock is bound to the entire source object and the source being a string it works out fine. The second textblock specifies the path as the length property

 

WPF Explicit Data Source Resource

WPF Explicit Data Source Resource

Data Contexts

Let’s see how we usually do data binding in WPF. With the use of data context we can hook up multiple controls to share the same source for the data bindings. We have set the data context property of the Grid. If the Source property is not set in the Data Binding then the Control looks for the Data Context. But there is no Data Context for the TextBlocks but just for the Grid. Data Context is an inherited property and the way It works is it flows down to the descendants so the textblocks inherit the data context from the grid. And this DataContext becomes the implicit source of these bindings and the bindings just specify the path.

 

WPF Data Context

WPF Data Context

You would notice that I have not specified the properties (Platform, Version and ServicePack) as path. This is valid as we saw in the previous section we used a constructor to specify the path same is the case here when xaml interprets these properties as the constructor arguments.

Let’s build a WPF App with Custom Class and Data Binding. Let’s create a class named Person and it will have two properties: Name and Age. Add the following code to the Person class. This class will act as a data source for us.

 

WPF Data Context

WPF Data Context

Now let’s design the User Interface for displaying the data. Add the following code the xaml. You will see that we have set the binding on the text property of the nameText and ageText to the Name and Age properties of the person class.

 

WPF Data Context

WPF Data Context

When we run the application we will see that the textboxes have picked the name and age properties.

 

WPF Data Context

WPF Data Context

As you know by default TextBox have the Binding Mode set as TwoWay. Let’s add a button to test this.

 

WPF Data Context

WPF Data Context

When we run this we will find that that when we click on show button after making the changes we will see that the value of the property is updated. But if we use the shortcut key Alt+S, we will see that the value of the property is not updated. The reason is that by default WPF updates the target when the focus is lost from the control. When we click the Show button by mouse the focus is changed from the textbox but when we use the Alt+S keyboard shortcut the focus is not changed and hence the target is not updated. To fix this we need to set the binding property named UpdateSourceTrigger to PropertyChanged on the textbox. So whenever the property is changed the source is updated.

 

WPF Data Context

WPF Data Context

When we run the application now and use the Alt+S we will see that the property is updated straight away. Now let’s see what happens when the source is updated. Let’s add another button to the view and a handler for it.

 

WPF Data Context

WPF Data Context

When we run this and click on Age + 1 button we will see that the textbox age value is not updated but when we click on show we see that the property is updated. The reason is that the data binding is not polling the property regularly as we have not told it to do so. So let’s the WPF know to poll the property. One way to do is to call the UpdateTarget on the Age + 1 button click.

 

WPF Data Context

WPF Data Context

Now when we run the application we will see that the display is also updated along with the property but this very crude way of updating the display. So let’s remove this UpdateTarget call from our code and let’s go to Person class and implement the INotifyPropertyChanged interface. This interface consists of a single event that gets raised anytime a property is changed. Also we modify the set accessor to call the change notification.

 

WPF Data Context

WPF Data Context

Now when we run the application everything works out to be fine.

Data Templates

It is very common for an application to show same kind of data over and over or show the same data at multiple places. WPF provides Data Templates for this purpose. So if we specify the Data Template for a class then that class can use it for displaying the data. The data template could work by just specifying it in the xaml along with the binding expressions.  Let’s copy the xaml from the previous sample and add it inside the data template.

 

WPF Data Context

WPF Data Context

And let’s add the following code to the code behind.

 

WPF Data Context

WPF Data Context

This way we have used data template for the task which were doing before using data template. To see the usefulness of the Data Template we need to add the following code to the code behind.

 

WPF Data Context

WPF Data Context

Now modify the xaml to make use of this data source which is a List of Person.

 

WPF Data Context

WPF Data Context

Here we have used the Person class as our item template but we can also set our item template property inline in xaml or when we specify our data template on the resources we might give it a key and then we can refer to that by using the key in the resource markup extension.

Data Triggers

There would be a requirement at times when you want to change some property of the control based on the change in value or data. So that is when Data Triggers come into picture as they will help us distinguish the data templates. Let’s see a Data Trigger in action. As we can see in the image below we have added a data trigger in Data Template so that whenever the value of the Age property becomes 21 the background of the label will change to Red.

 

WPF Triggers

WPF Triggers

Triggers are pretty basic and they can only check constant value. We cannot do any complex checks with triggers. But we can take care of that via ValueConverters.

We can also use data triggers to trigger animation. Just add the code below to the xaml file.

 

WPF Triggers

WPF Triggers

We can also use EventTriggers or MultiTriggers in DataTemplates as well.

Binding To Collections

As we can see in the image below we have binded the ListBox to a Collection of SystemFontFamilies. You will also notice that we have not set the binding here just mentioned the static resource. The ItemsControl does not mind this until its getting a collection in return to bind to. We have set the Data Template inline. Here we have bound the TextBlock to a Non Text property which is the Font Family object itself. All ItemsControl (ListBox, ComboBox, ListView, TabControl, TreeView, Menu) support this kind of binding. We should be cautious not to add any items to its children or to its items property if we have used the ItemsControl property. An ItemsControl must be either used in the DataBound mode or the normal mode. Otherwise addig items to the ItemsSource while it already has children will result into exception.

 

WPF Collection Binding

WPF Collection Binding

Master Details of Selected Item

We might often want to showcase additional detail of the item selected. Let’s take help of an example to showcase this. Add the code shown below to the xaml. The ListBox part of the code is quite similar to the previous section except one additional property IsSynchronizedWithCurrentItem. This is because the data binding susyem will keep track of currently selected item data source and these controls are not required to sync with that so we want them to be in sync. We have also used the textboxes to display these additional details and you would see that we have bound the text property of the textboxes to a single property and this property is not present in the collection which is set to data context. So the data binding system checks if this property is present in the currently selected item and as it does it displays that value.

WPF Additional Info Binding

WPF Additional Info Binding

So we are relying on the data binding to fail in 1st attempt in order or the data binding to work. So we can fix that by adding a / to the binding and this will mean we want to bind with the currently selected item.

 

WPF Additional Info Binding

WPF Additional Info Binding

You might also notice that we have used [en-us] in the FamilyNames textblock this is because the Font Name sis a dictionary and it has different values in different culture and we are passing the locale to look entry in the dictionary. We can also dig down into sub properties by using the . syntax.

Hierarchical Binding

Sometimes we might want to bind to a data source which has child items and we would want to them to display as well so we can use Hierarchical Binding in that case. Let’s see this in action. So we have created a XmlDataProvider in Grid.Resources and then referenced it into the Hierarchical Data Template of the treeview.  And insideproperty of that we have a textblock whose text is set to xpath as title and the hierarchical data template’s itemssource property is set to xpath item. The item expression will select all the child elements called items. The same technique works for menus as well. This xml data provider can be inline or external.

 

WPF Hierarchical Binding

WPF Hierarchical Binding

The Data binding system does not make a big distinction between the xml data binding and xml data binding. We can actually mix them. Let’s see that in action. So change the XPath to Path in the TextBlock and then look at the NodeType or InnerXML or Value. So for data binding these are just objects. We can also use ordinary property style binding and xml data binding together.

Since the XMlDataProvider just uses the XML.Dome classes from Syem.XML namespace we can use the following code in the code behind to load the xml directly into the data context.

 

XML Namespaces

This is where binding with XML gets complicated. If we are not using any namespaces the xml data then the xpath would just work with the document classes. So as seen below the expression works fine with a document with no namespace but if the same expression is run with the same document but namespace then the query will return nothing.

 

We can use namespace aware syntax to do the proper data binding. We cannot specify the namespace of xml as we use to refer types in xaml. Instead we will have to use the XmlDataProvider.XmlNamespaceManager and then use the helper class XmlNamespaceMappingCollection. Then we add the Prefix as the xml namespace reference.

 

WPF XML Namespaces

WPF XML Namespaces

CollectionView

Every time we bind a ItemsControl to an XML node or an object WPF creates a collection view. This is object that manages that collection for the data binding purposes. Actually it’s the CollectionView that knows the currently selected item for that CollectionView. The CollectionView sits between the Source and the View and provides other services like data sorting, callback functions to fill the view and data grouping.

Let’s see the grouping service of the collection view at work. Add the following code your xaml file. We have to tell the collection view about our grouping requirements. Now you should remember that the collection view is always created at runtime so we cannot access it in xaml directly. So instead we have to use a collectionViewSource. This is the description in xaml that tells WPF to how to configure the CollectionView. So we have binded the collection view to the data source and grouped it from the GroupName attribute. We can have more than one CollectionViewSource for any collection. Also the controls will have to specify this CollectionView as their View Source to override the default view to that specified by the CollectionView.So we have set the ItemsSource of the MenuItem to our collection ViewSource. By default all ItemsControl have the abailty to put headers in groups and we can do this by specifying a group style which uses a data template. So we have use dthe grouping information coming from the CollectionView Source.

 

WPF Collection View

WPF Collection View

INotifyCollectionChanged

This is the interface similar to INotifypropertyChanged this interface reflects the collection level changes and its already implemented in the ObservableCollection. So this will works with Lists so when the items change on the complete list this will send the notification.  If we use a list and add items to it then the same will not reflect on the user interface even we have data binding but if we use an ObsevableCollection in the place of List we will see the changes.

Converters

Sometimes the data might not be directly suitable for the data binding. So we might want to need to convert it before it reaches the data binding. So this where the converters come into picture. All Converters in WPF bindings implement the IValueConverter. This interface has a Convert and ConvertBack method. The convertback method gets used in twoway bindings. Converters are very simple. They just get to adjust or replace data that flows between the source and the target.

Let’s see this in action. WE will be using the person class we created earlier. Add the following code to the xaml for the window.

 

WPF Converters

WPF Converters

WPF Converters

WPF Converters

 

And the following code to the code behind file.

 

WPF Converters

WPF Converters

Now create another class in the application named AgeCheckConverter.cs and add the following code to it.

 

WPF Converters

WPF Converters

You will see that we have used this converter in our DataTrigger and checked for value true. The converter does the actual logic and we get the red background if the age is less than 21. Also coverters helps us put the logic for the decision making.

Validation

The data binding system also has support for validation. We can add a set of validation rules for our binding. But to do that we need to use the syntax of binding in full. Validation rules are pretty simple. All they do is look at a value and say whether its valid or not. As we see in the example below the validations will derive from the ValidationRule base class and override the Validate method. You can see the validation rule has no context. It just gets the value. But the problem is that this validation system does not work with the multi field validations. Its more useful at places where we verify whether the strings has the required format or not.

Let’s see this in action. Add a class named MySource.cs and implement the IDataErrorInfo to do the validations.

 

WPF Validation

WPF Validation

Add the following code for the view

 

WPF Validation

WPF Validation

And add the following code behind

 

WPF Validation

WPF Validation

We will see that the textbox border becomes red when a validation error occurs.

 

Other Binding Types

We can also use Multi bindings which lets us combine multiple source values into one result so we can provide it with the connections to ordinary bindings one for each source value and then we need to provide a Multivalue converter that implements IMultiValueConverter.

Another binding is Priority binding which is used by WPF one after another until it finds a binding that works.

 

The Code for the post can be found here.

 

Any Questions, comments and feedback is most welcome.

 

 

This line of tutorials will take you through all the ASP.NET fundamentals

Architecture of ASP.Net

How an ASP.NET page is processed?

All the asp.net pages are parsed into a class definition and that class is then compiled into a.Net assembly who sole purpose is respond to request destined for the endpoint. This class is then loaded into the worker process i.e. w3wp.exe and the classes will then be created and will process the requests. These classes are created on demand and this happens for all the .aspx. So it’s safe to say that when you are writing an .aspx you are writing a class. So essentially when we are writing aspx we are just building additional classes and extending the base classes and controlling the class generation from .aspx files.

Let’s see this in action. I hope you have IIS installed on your machine. So just go to cà inetpub à wwwroot and create text file named HelloWorld.aspx and add the following content to it.

<html>
<h1> Hello World!!! </h1>
</html>

 

And then save it and close it. Now go to the Internet Explorer and type the following:

http://localhost/helloworld.aspx

And you will see something like below:

 

HelloWorld.aspx

HelloWorld.aspx

Now let’s understand what going on here. Let’s first add the code as shown below to the HelloWorld.aspx. The Page Directive will set the language as C# and also the Debug to true. Also we will access the GetType().Assembly.Location method as we know we are in .NET and we will be able to track the location of the class.

<%@ Page Language="C#" Debug="true" %>
<html>
<h1> Hello World !!! </h1>
<h3> This Page is loaded from
<%= GetType().Assembly.Location %>
</html>

 

The %= is the evaluation syntax in the server side script <%= GetType().Assembly.Location %>

Now when you will refresh the page, you could see the location from where the assembly was loaded along with the name of the assembly.

 

Temporary ASP.NET Files

Temporary ASP.NET Files

Now when we open up this directory (E:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\a2cc4162\951dc92c)

Temporary ASP.NET Files Directory

Temporary ASP.NET Files Directory

you could see that C# source code files are present here and if you open them you could see the class definition present in it. As you could see the name of the class is created by replacing the . with an _ and it derives from System.Web.UI.Page which is the base class for all the aspx pages.

ASP.NET generated Code file

ASP.NET generated Code file

Now if we scroll down the file we could see how the html is parsed and the method that we wrote injects the content.

 

ASP.NET generated Code file

ASP.NET generated Code file

Dynamic Content

Now as we could see in the image below, we could see Interspersed script notation which is root cause of many problems in a web site so we do not want to follow this as a practice at all. This syntax is still supported but we will try to move towards other techniques for easier to maintain code.

 

ASP.NET Dynamic Content

ASP.NET Dynamic Content

So the types of dynamic content that we can integrate onto our page is

  • Interspersed server-side script – So this is the way of dropping code onto the page but the language will be as specified in the page directive. It has to be in the language specified at the top of the page. Then we also have the evaluation syntax (GetDisplayItem) which is equivalent to Response.Write.
  • Server side scripts – So we can also include server side scripts as a block with the Runat sever attribute so that it is dumped into the class definition.

Let’s just add the following code to the HelloWorld.aspx from the previous example.

<%@ Page Language="C#" Debug="true" %>
<script runat="server">
const int _itemCount = 10;
string GetDisplayItem(int n)
{
    return "item #" + n.ToString();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Dynamic Content</title></head>
<body>
<h1> Hello World !!! </h1>
<h3> This Page is loaded from
<%= GetType().Assembly.Location %></h3>
<ul>
<% for (int i=0;i<_itemCount; i++)
{ %>
<li><%=GetDisplayItem(i)%></li>
<% } %>
</ul>
<%
Response.Write("<h2>Total Number of items = "
+ _itemCount.ToString() + "</h2>");
%>
</body>
</html>

 

When we run the page we would see something like below:

 

ASP.NET Server Side Script

ASP.NET Server Side Script

 

Let’s go back to the directory and have a look at the generated content once again. So what we see here is that the server side code is injected directly into the code file. So whenever we use server side scripting then that is dropped into the class directly. So we used put only those things in server side scripting that would make sense if they are in the class definition directly. So we could not directly executable code in class definition.

 

Generated server side script ASP.NET

Generated server side script ASP.NET

And the client code is added to the function definition that will write onto the screen. So the code that was part of Interspersed script is put directly into a function within our class. We could not define function here as nested function definition is not allowed in C#.

 

Generated server side script ASP.NET

Generated server side script ASP.NET

Server Side Controls

We should avoid using Interspersed scripts as it tends to clutter pages and makes the code difficult to maintain. We should try to use the preferred model for dynamic content in an ASP.NET page. This model comes from the server side controls in ASP.NET. So any control that has a runat=”server” attribute will be added to the class definition as a server side member variable, so we could manipulate these variable instead of the Interspersed scripts. The state maintained for the Server side controls is implicitly POST to the same page.

Let’s revisit our page and replace the server side scripts with server side controls. Let’s first replace the dynamic generated script with the server side control definition. We are following a common technique of populating the server side control with some content even though this content will never be displayed. So we are using a server side control named bulleted list which will display an unordered list.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

Now we are going to write a method to populate this list. So we are overriding the OnLoad method which we inherited from the page base class. So we are using the already created list _displayList and clearing the items in it. Then we are iterating through the items and add the items to the _displayList.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

If you will run this page now you will get an error saying that the runat=”server” controls should be placed in the form with a runat=”server” attribute. So let’s add that.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

And now we run the page we will something like below.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

Let’s also have a look at the class definition changes with the addition of the server side controls. The very first thing that you will notice is that the BulletedList named _displayList is added as a protected member. And the interaction with that _diasplayList member is shown below it.

 

ASP.NET Server Side Controls

ASP.NET Server Side Controls

Data Binding

In the previous section we edited the server side control at very low level but we can also use ASP.NET data binding model. So we will add a string array of the items we want to show. It has to be an Enumerable collection. It can be an array, dataset, datatable, strongly typed list class, etc. So all we need to do is the ItemsSource property to the collection we want to bind to and then exclusively call DataBind(). Let’s see the code of the same.

 

ASP.NET Data Binding

ASP.NET Data Binding

We will see a similar output if we run this page but instead of iterating and adding the items we have utilized the power of data binding.

Declarative Data Binding

Version 2.0 of .NET introduced data source controls. The idea behind declarative data binding is that instead of manually writing the code for data binding we hand it off to another control. In this case we will have a look at the ObjectDatSource as this lets us point the datasource to a class definition. To use it we have to specify the name of the class to use and the name of the method that will be used to retrieve the data. So now our page will not have any data access code as all that logic is separated to a separated class. So let’s write the code for this. Let’s go to the wwwroot folder and create a directory named App_Code. This is a special directory because if we place any source code files in this directory they will be implicitly complied if they are referred any of our pages. We will then add a file named ItemsDataSource.cs

 

ASP.NET Declarative Data Binding

ASP.NET Declarative Data Binding

We will remove all the server side code as it will be handled by this declarative data source. And then let’s wire up to the ItemsDataSource. We have added an object data source as MyDataSource and refer it in the BulletedList. So now when the list needs the data it will go and query the mentioned object data source which will in turn query the specified method in the specified class.

 

ASP.NET Declarative Data Binding

ASP.NET Declarative Data Binding

Code Behind V2.0

The ASP.NET version 2.0 code behind model is like shown below. We have specified in our aspx page the code behind for this page. Also we have the concept of partial class implemented for these classes.

 

ASP.NET Code Behind

ASP.NET Code Behind

Let’s change our code accordingly. Let’s add a new file names hellocodebehind.aspx.cs and move our code which not related to the presentation to this file.

 

ASP.NET Code Behind

ASP.NET Code Behind

Page Lifecycle

So now we have the ability to separate the code from the view as we saw in the previous section. Let’s understand the ASP.NET page lifecycle which is shown in the image as below. This will help us understand many other things that can be done inside the page class definition. Just refer the aspx.cs class that we wrote earlier and you will see that we have overridden the OnLoad event of the page. This is one of the events that take place while processing the request for the page and this is most common of the events in which users generally tap into for doing data binding modifying controls and there values. There are many other events that occur during the complete page request process as we could see in the image below. When a request for an aspx page is made then class is constructed and its constructors will be called and then this lifecycle sequence is launched starting from the top left to the bottom right. Another event for which handler is added is very commonly is Init. This event occurs early in the lifecycle of the page but after all the controls have been loaded into the control tree. Another event is the LoadComplete event which is fired after all the server side events have been fired. Pre render is a back stop which takes place just before the rendering is sent to the client. PreInit is the only event where we can edit master pages and themes. Render event occurs when the response is sent back to the client. Once the response is sent back to the client then Unload events occurs.

 

ASP.NET Page Lifecycle

ASP.NET Page Lifecycle

Event Handling

Let’s talk about how we can wire up events. This is the techniques that can be used to wire up all the events in the page class. The naming convention for such events is On followed by the name of the event.

protected override void(EventArgs e)
{
    base.OnLoad(e);
}

 

In Visual studio the standard techniques when using Visual Studio is to create a function named Page_ followed by the name of the event and .Net will implicitly add a delegate subscription. This function is called as the Auto Event Wire Up and this is the preferred model in Visual Studio.

protected void Page_Load(object sender, EventArgs e)
{
}

 

Another way of accessing this events is to access these events as the members of the Page class. Simply .NET events defined on the System.Web.UI.Page Base class and all we need to do is use += to add a delegate.

this.Load += new EventHandler(EventPage_Load);
this.Load += EventPage_Load;
void EventPage_Load(object sender, EventArgs e)
{
}

 

So let’s see this in action. Let’s modify the HelloWorldCodeBehind.aspx to use the AutoEventWireUp.

 

ASP.NET Event Handling

ASP.NET Event Handling

Now let’s make use of Auto Event Wire up and tap into the LoadComplete event. We need to modify the HelloWorldCodeBehind.aspx.cs for this as below.

 

ASP.NET Event Handling

ASP.NET Event Handling

When we run this page we will see that the text is written at the top of the page.

 

Method Name for Implicit event subscription

The way AutoEventWireUp wire works is through the hashtable defined in the .NET. At runtime a check is made for the strings present in the code to match up with the string shown in the table below. So there is no algo for. So it’s just a set of hard wired strings that are looked for automatically when AutoEventWireUp property is set to true. This will work only if the signature also matches up with the event.

 

ASP.NET Event Handling

ASP.NET Event Handling

 

Control Event Handling

Other events that we will be handling in code are the events are raised by the controls on the page. So the recommended model for handling a control initiated event is go to the server side control in the view and add a prefix On to the event name and then set the handler for it. That handler in the code should have the correct signature of an event.

<asp:Button ID="ClickMeButton_Click" runat="server" Text="Click me!" onClick="_clickMeButton_Click" />

 

protected void ClickMeButton_Click(object sender, EventArgs e)
{
}

 

The other way to do it is use the += notation the code class to specify the handler for a particular event.

Let’s see this in action. Add a button and a label at the bottom of the HelloWorldCodeBehind.aspx file as shown below.

 

ASP.NET Control Event Handling

ASP.NET Control Event Handling

Now let’s go to the server side code i.e. HelloWorldCodeBehind.aspx.cs and add a handler for this button click event.

 

ASP.NET Control Event Handling

ASP.NET Control Event Handling

When we run the page we will see something like below.

 

ASP.NET Control Event Handling

ASP.NET Control Event Handling

Compilation

Another feature that was added to .NET 2.0 was the suite of directories as shown below.

  • App_Code directory is the place where we place the code and it automatically compiles as part of the aspx page request process.
  • App_Browsers directory is used for defining additional .browser files which define the additional browser capabilities.
  • App_GlobalResources directory automatically compiles .resx files into the application.
  • App_LocalResources directory automatically compiles .resx files into the application.
  • App_Themes directory is used for referencing themes in the site
  • App_WebReferences directory is where wsdl files are placed.

The version 2.0 ships with a  new compiler named aspnet_compiler.exe which helps us compile our directories manually into binary deployment files. Below is the detailed chart of all the directories and there usages.

 

ASP.NET Compilation

ASP.NET Compilation

Shadow Copying

The mechanism of shadow copying is import for the deployment, updating, etc. The idea behind it is this that we do not have to shut the site to deploy the new binaries. In classic ASP we need to shut down the server in order to release the references so that we can copy the new binaries without any errors. With version 2.0 we do not have to do that because of Shadow copying. As we can see in the diagram below when we try to access a binary what ASP.NET does is physically copies the binary to an obfuscated location and then runs so that there is no direct reference to the binary and also when the binary is updated then it updates the binary as well.

 

ASP.NET Shadow Copying

ASP.NET Shadow Copying

 

You can find the code for this post here.

 

Any questions, comments and feedback is most welcome.

 

 

 

 

Working with Data in Expression Blend 4

Element to Element Data Binding

In this section we are going to see how we can use data binding in Expression Blend. We will see how we can create sample data sources and how to use them in data binding.

Data binding is a functionality that both Silverlight and WPF have that helps us set the property of an element to an external data source. That data source can be xml if we are using WPF and can be any CLR object if we are using Silverlight or WPF. It could also be a sample data source. When we apply data binding to an element then that element does not get its value directly but it has to go to some other location for getting its value. This other location can be another element or a database or an xml.

  • Let’s have a look at the element to element data binding. Open Expression blend 4 and create a new Silverlight Project.
  • Now go to the tools pallet and select rectangle.
Expression Blend 4 : Rectangle

Expression Blend 4 : Rectangle

  • Now create a rectangle by pressing the left button of the mouse and dragging it on the artboard.

 

Expression Blend 4 : Rectangle

Expression Blend 4 : Rectangle

  • Now go to the properties of the rectangle and set the horizontal alignment to stretch and left and right margins to 0.

 

Expression Blend 4 : Rectangle Properties

Expression Blend 4 : Rectangle Properties

  • Let’s go back to the tools pane and grab a slider and drop it on the artboard.

 

Expression Blend 4 : Slider

Expression Blend 4 : Slider

  • If you have a look at the properties of the slider you would see values like Maximum (The maximum value of the slider), Minimum (the minimum value of a slider), SmallChange (the value that will change when user has focused the slider and uses the up and down arrow key to change the value of the slider), LargeChange (the value that will change when do a mouse click at any location on the slider track). Let’s set these properties as shown below.

 

Expression Blend 4 : Slider Properties

Expression Blend 4 : Slider Properties

  • Now let’s setup the data binding. There are two ways to set the data binding: one way or two way. In one way data binding only one property can change the other but not vice versa. In two way data binding both the properties can change each other. In this case we want only one way binding so that the width of the rectangle can change on the change in the slider. So let’s select the rectangle and go to the width property and click on the property marker next to it.
Expression Blend 4 : Rectangle Property Marker

Expression Blend 4 : Rectangle Property Marker

 

  • And select element property binding.

 

Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

  • Now our cursor has been moved to the object picker mode so we need to point to the element with which we want to do the property binding. In this case we will move our cursor to the slider and click on the slider.

 

Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

  • Once we will click on the slider we will get an option select which property of the slider we want to bind to and we will select value.

 

Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

  • The moment we do this we see that the width of the rectangle is changed and the Width property has a yellow rectangle around it showing that this property is getting its value from some other location.
Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

 

  • Now we can run the application and see that the width of the rectangle will change as we change the slider value.

 

Expression Blend 4 : Element Property Binding

Expression Blend 4 : Element Property Binding

Two Way Data Binding

In this section we will see how we can create two way data binding. Along with the Slider we will provide a textbox to modify the width of the rectangle.

  • Let’s drag out a textbox on to the artboard.

 

Expression Blend 4 : Element Property Binding Two Way

Expression Blend 4 : Element Property Binding Two Way

  • Now go to the text property of the textbox and click on the property marker and select Element Property Binding.

 

Expression Blend 4 : Element Property Binding Two Way

Expression Blend 4 : Element Property Binding Two Way

  • Select the slider control again and select its value property again as we did in the case of the rectangle. Also we will select the TwoWay Binding so that both the controls i.e. TextBox and Slider can change each other’s value.

 

Expression Blend 4 : Element Property Binding Two Way

Expression Blend 4 : Element Property Binding Two Way

  • Now we can run the application and change the value of the slider or textbox and we will see that the width of the rectangle is changing and the other control’s value is also updated.

Data Binding with Data Sources

 

In this section we will see how we can use data binding with data sources. Data sources can either be xml or any other CLR object. As we know that xml works only with WPF so for this demo we will have to use data binding with sample data. When we work on an actual project we have CLR objects in which data is stored and they definitely follow some schema. So we can build up sample data in Blend to represent that sample data. So let’s get started.

  • Create a new project in Blend. Navigate to the data tab in the right panel. If the data tab is not visible then goto the window menu of blend and select data.
Expression Blend 4 : Data

Expression Blend 4 : Data

  • Click on the Create Data Source.

 

Expression Blend 4 : Create Data Source

Expression Blend 4 : Create Data Source

  • And select New Sample Data. You will also see option to create Sample data using XML or Class. If we have those then we can use them. When we select any of those two options then blend will not exactly use those but take them as a basis for generating sample data.

 

Expression Blend 4 : Add new Sample Data

Expression Blend 4 : Add new Sample Data

  • Give the Sample Data Source some name and select the define in as project. We do want to enable sample data when application is running so keep It checked.
Expression Blend 4 : Add new Sample Data

Expression Blend 4 : Add new Sample Data

 

  • When we click ok we will see that the data source appears in the data tab at project level and we have a collection with properties in it.

 

Expression Blend 4 : Sample Data

Expression Blend 4 : Sample Data

  • We can also see that in the Projects that a new folder is added named SampleData. When we expand it we see that there is a xaml in it which will store all the data and an xsd which is the schema.

 

Expression Blend 4 : Sample Data Folder

Expression Blend 4 : Sample Data Folder

  • If we open the MyAddresses.xaml, we will see that we have some items already added in the data source. We modify their values or add new items.
Expression Blend 4 : Sample Data xaml

Expression Blend 4 : Sample Data xaml

 

  • Let’s go back to the data tab and click on Edit Sample Values as shown in the image below.
Expression Blend 4 : Edit Sample Data

Expression Blend 4 : Edit Sample Data

 

  • We will see something like below. We can edit the values or the types of these properties.

 

Expression Blend 4 : Edit Sample Data

Expression Blend 4 : Edit Sample Data

  • Let’s rename the properties as shown below. Also lets change the specification of the Address property as shown below.
Expression Blend 4 : Edit Sample Data Property Type and Format

Expression Blend 4 : Edit Sample Data Property Type and Format

 

  • Also similarly change the Format of name to Name. When we do that if you go back to Edit Values we will see that the data is has been populated according to the format selected.

 

Expression Blend 4 : Edit Sample Values

Expression Blend 4 : Edit Sample Values

  • Let’s add email, phone number  and CustomColor properties.Also modify the format accordingly
Expression Blend 4 : Edit Sample Values Format

Expression Blend 4 : Edit Sample Values Format

 

  • And we will see data something like below.

 

Expression Blend 4 : Add Properties in Sample Values

Expression Blend 4 : Add Properties in Sample Values

  • Now let’s start using this data that we have created. Drag and drop the Collection onto the artboard.
Expression Blend 4 : Create Databound ListBox

Expression Blend 4 : Create Databound ListBox

 

 

  • And a listbox will be automatically created. And each entry will show all the fields. Also the yellow rectangle around the datasource shows data binding.

 

Expression Blend 4 : Create Databound ListBox

Expression Blend 4 : Create Databound ListBox

  • Let’s improve the look of the List Box by the use of Data Template. Right Click the ListBox and Go to Edit Additional Template à Edit Generated Items (ItemTemplate) à Edit Current

 

Expression Blend 4 : Edit Generated Items

Expression Blend 4 : Edit Generated Items

  • We would something like this. Let’s delete the Color textblock as we do not want to display the color in this way. When we delete that textblock you would see that that textblock is deleted from each item and that’s the way templates work.

 

Expression Blend 4 : ListBox DataTemplate

Expression Blend 4 : ListBox DataTemplate

  • Now let’s select the listbox from the breadcrumb bar and stretch it.
Expression Blend 4 : ListBox DataTemplate

Expression Blend 4 : ListBox DataTemplate

 

  • Now let’s go back to the template and change the  orientation of the stackpanel to horizontal from vertical. And then build the solution. We will see something like below.

 

Expression Blend 4 : StackPanel Orientation

Expression Blend 4 : StackPanel Orientation

  • Lets give specific width to all the textblocks and we will see a clean layout.
Expression Blend 4 : StackPanel Orientation

Expression Blend 4 : StackPanel Orientation

 

  • Let’s delete all the textblocks except the Name TextBlock. Then let’s go back and select the listbox and reduce its width.

 

Expression Blend 4 : DataContext

Expression Blend 4 : DataContext

  • Now go to the data tab and select the view mode to details view.

 

Expression Blend 4 : DataContext

Expression Blend 4 : DataContext

  • Now let’s drag the Name field on to the art board. We will see that a grid is created along with textblock as its child. Now whenever we select the item in the listbox we will see that the content of the textblock in the grid is changing. This happens because the grid that got created has a concept called Data Context. The grid has its data context set to the list box. So as soon as an item is selected in listbox then the the value changes in the grid as the items in the grid have already specified what item of the listbox they want to display. We can other fields as well in the grid and see that their value change as the selection of the listbox changed.

 

Expression Blend 4 : DataContext

Expression Blend 4 : DataContext

  • When we run the application we will see something like below.

 

Expression Blend 4 : Run App with Sample Data

Expression Blend 4 : Run App with Sample Data

  • Lets go to the grid à Background à Property marker à Data Binding. We will a window like below.

 

Expression Blend 4 : Data Binding Background

Expression Blend 4 : Data Binding Background

  • Select Customcolor string and the background of the grid is bound to the color string of the selected item. The value conversion is going on in the background.

 

Expression Blend 4 : Data Binding Background

Expression Blend 4 : Data Binding Background

  • When we run the application we see something like below.

 

Expression Blend 4 : Data Binding Background

Expression Blend 4 : Data Binding Background

The code for this post can be found here.

 

Any questions, comments or feedback are welcome.

 

Microsoft has been offering data binding for all its user interface applications but it was an assumption that all the data binding that will happen will always be related to database. However WPF and Silverlight have a broader view assuming that the client side code is often not connected directly to the database. And Silverlight goes a step further by not providing the ADO.NET classes to connect to the database directly. This makes sense because Silverlight is used to design web pages and most organizations do not want to put their database onto the internet for obvious security reasons. So the way data comes into a Silverlight application is in the form of objects or xml. So the data biding framework in Silverlight focuses on objects. So the purpose of data binding is to connect the features of UI to the properties of the objects. Databinding can be used with nearly any property of any element.

Binding Expressions

To bind the property of a user interface element we use the binding markup extension. As you can see in below markup extensions are specified in the curly braces which are evaluated at runtime.

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname}”/>

 

So this markup binding extension binds the path property of the TextBox to property named Surname and the value of this TextBox text property is evaluated at runtime. Data binding will always connects 2 properties: the target property (generally the user interface property) and the source property (a dependency

Data Context

Now as we saw in the last section that we need to provide the data binding along with the source and target property. So if want to bind multiple targets then we do not need to write the source individually for each of the target property as multiple targets can use the same source for data binding. Let’s have a look at this with an example.

Let’s create a Person class in you user interface with the following Fields as shown below.

namespace DataBindingInSL

{

public class Person

{

public string GivenName { get; set; }

public string Surname { get; set; }

public double Age { get; set; }

}

}

 

Now we want to bind these properties in the User Interface. So lets add the following code in the code behind file of the view.

namespace DataBindingInSL

{

public partial class MainPage : UserControl

{

Person src = new Person { GivenName = “Max”, Surname = “Smith”, Age = 34 };

 

public MainPage()

{

InitializeComponent();

 

this.DataContext = src;

}

}

}

 

Now we are setting the DataContext of the User Interface as src.  By setting the DataContext property at the root element we have made the properties available at the all the elements in the tree as the DataContext in Silverlight cascades down the tree.  We could also set the datacontext on any panel as well and in that case the datacontext will apply only to the panel and its children. Once we have set this DataContext, it becomes the implicit source for all the user Interface elements. So in the View all we need to do is the property name in the binding path and the element will pick up the property from the source i.e. Data Context. Add the following code to the xaml of you SL app.

<Grid x:Name=”LayoutRoot” Background=”White”>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″ Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName}” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″ Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname}”/>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″ Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age}”/>

</Grid>

 

When you run the application you would see that all the TextBox will display the values that are picked up from the bindings.

Data Context Silverlight 4

Data Context Silverlight 4

Right now the data is flowing in only one direction i.e. from src to the User Interface. If we want the data to flow in both the directions then we need to specify the mode as TwoWay in the Binding as shown below:

Text=”{Binding Path=Age, Mode=TwoWay}”

 

Binding Updates

As we saw in the last section that the User interface is updated with the values that are set in source at load time but when the values are updated at a later point in time then also the data binding model of Silverlight can reflect the in the source to the user interface when the data source raises change notification. The change notification can be raised after implementing the INotifyPropertyChanged.

So let’s implement the INotifyPropertyChanged interface in the data source so that whenever the source changes the User Interface is updated along with it as well. This interface has only one event which is raised whenever a property changes in the class. So change the code of the Person class as below along with the implementation of INotifyPropertyChanged.

public class Person : INotifyPropertyChanged

{

public string GivenName { get; set; }

public string Surname { get; set; }

private double _age;

 

public double Age

{

get { return _age; }

set

{

if (value != _age)

{

_age = value;

OnPropertyChanged(“Age”);

}

}

}

 

public event PropertyChangedEventHandler PropertyChanged;

 

private void OnPropertyChanged(string propertyName)

{

if (PropertyChanged != null)

{

PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

}

}

}

 

Here after the implementation of INotifyPropetyChanged we change the code inside the set method of the Age property to call the OnPropertyChanged method which in turn raises the property changed event. So now when the Age property is changed the change will reflect in the User Interface as well. Change the code of the cs and xaml file to as shown below and you will be able to see the update in the property.

 

Silverlight 4 Binding Updates

Silverlight 4 Binding Updates

Data Template

We have seen the example of an adhoc binding in the previous section but Silverlight has a more structured way of defining the same using Data Template. A Data Template is similar to a Control Template. Just as the control Template determines how the Control should like, in a similar way a Data Template determines how the particular data would look like. Data Templates can be used by ItemsControls (ListBox, etc) and ContentControl (Buttons, etc). A Data Template will work at any place where a Content Model is in place.

Whenever there are custom properties in a class then it’s a good idea to define a Data Template in xaml so that the control knows how to display those types.  Let’s see this working in code.

<UserControl.Resources>

<DataTemplate x:Key=”dataTemplateBinding” >

<Grid>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″

Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″

Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″

Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName, Mode=TwoWay}” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname, Mode=TwoWay}”/>

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age, Mode=TwoWay}”/>

</Grid>

</DataTemplate>

</UserControl.Resources>

<Grid x:Name=”LayoutRoot” Background=”White”>

<ContentControl Content=”{Binding}”

ContentTemplate=”{StaticResource dataTemplateBinding}” />

<Button Content=”Older” Height=”23″ HorizontalAlignment=”Left” Margin=”43,242,0,0″

Name=”button1″ VerticalAlignment=”Top” Width=”75″ Click=”button1_Click” />

</Grid>

</UserControl>

Binding to Collections

Instead of binding to one instance we can bind a control to a collection. Let’s modify the MainPage as below to create a collection of Person.

public partial class MainPage : UserControl

{

Person src = new Person { GivenName = “Max”, Surname = “Smith”, Age = 34 };

List<Person> people = new List<Person>();

 

public MainPage()

{

InitializeComponent();

 

people.Add(src);

people.Add(new Person { GivenName = “Steve”, Surname=”Gaylon”, Age=44};

people.Add(new Person { GivenName = “John”, Surname=”Miller”, Age=14};

 

this.DataContext = people;

}

 

private void button1_Click(object sender, RoutedEventArgs e)

{

src.Age += 1;

}

}

 

Let’s change the xaml as below:

<UserControl.Resources>

<DataTemplate x:Key=”dataTemplateBinding” >

<Grid>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″

Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″

Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″

Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName, Mode=TwoWay}” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname, Mode=TwoWay}”/>

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age, Mode=TwoWay}”/>

</Grid>

</DataTemplate>

</UserControl.Resources>

<Grid x:Name=”LayoutRoot” Background=”White”>

<ListBox ItemsSource=”{Binding}”

ItemTemplate=”{StaticResource dataTemplateBinding}” />

<Button Content=”Older” Height=”23″ HorizontalAlignment=”Left” Margin=”43,242,0,0″

Name=”button1″ VerticalAlignment=”Top” Width=”75″ Click=”button1_Click” />

</Grid>

 

Collection Updates

The INotifyPropertyChange will work only when a property is changed but when a collection is changed we need to implement the INotifyColectionChanged. We can either use ObservalbeCollection<T> or implement this interface to get the update whenever a new item is added to the collection.

Let’s add a new button along with a new event handler to add a new item to the collection so we need to change the xaml and cs file to as below:

private void button2_Click(object sender, RoutedEventArgs e)

{

people.Add(new Person { GivenName = “Scott”, Surname = “D”, Age = 62 });

}

 

<Button Content=”Add Item” Height=”23″ HorizontalAlignment=”Left” Margin=”325,182,0,0″

Name=”button2″ VerticalAlignment=”Top” Width=”75″ Click=”button2_Click” />

 

Now replace the List<Person> with ObservableCollection<Person>.

ObservableCollection<Person> people = new ObservableCollection<Person>();

 

And that is it. Now whenever you click the Add Item button a new item will be added to the collection and also the ListBox will be updated.

 

Grouping

If we want to group the data based on some criteria then we can use the CollectionViewSource. This groups the items based on the property specified of the items.

<UserControl.Resources>
    <CollectionViewSource x:Key="mySource" Source="{Binding Path=RawItems}">
        <CollectionViewSource.GroupDiscussions>
            <PropertyGroupDiscription PropertyName="EventTrack" />
        </CollectionViewSource.GroupDiscussions>
    </CollectionViewSource>
</UserControl.Resources>

 

DataGrid internally understands grouping but the ItemsControl does not. So this is an advantage as by using the ItemsControl we can have our own custom visualizations.

 

Silverlight 4 Grouping

Silverlight 4 Grouping

When we wrap a collection in a collection view source, it provides a property known as groups.  Normally we can bind to a wrapper but we can bind to the groups property instead.

<ItemsControl ItemsSource="{Binding Path=Groups, Source={StaticResource groupSource}}">
    <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding Path=Items}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

Silverlight 4 Grouping

Hierarchical Binding

The basic ability to bind with hierarchical controls is provided by the HeadedItemsControl class. HeadedItemsControl derive from ItemsControl so the binding works in nearly the same way. The difference is in the ItemTemplate property as need to refer to HieraricalDataTemplate instead of a normal DataTemplate. The Hierarchical Data Template has one feature. It too has a ItemsSource Property.

<sdk:HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
    <TextBlock Text="{Binding Path=Label}" />
</sdk:HierarchicalDataTemplate>

Silverlight 4 Hierarchical Binding

 

Find the source code ralated to this post here.

 

Any questions, comments and feedback are most welcome.