DependencyObject

DependencyObject provides WPF property system. The WPF system needs the needs the properties to have a richer set of services like change notification is required for triggers and data binding. So apart from Change Notifications we also need Default Values, Type Coercion, Data Binding, Attached Properties, Validation, Inheritance down the Visual Tree and Styling to be available for the properties. It’s not feasible to implement all these features to a property every time we use it, so it’s really helpful to have these features already present in the properties. DependencyObject is the base type of most of the types we work in WPF and hence they already have all these features of the DependencyObject.

DependencyProperty

To use a dependency Property we need to do the following things.

  • Derive from DependencyObject
  • Register the DependencyProperty by passing the name of the property, the type of the property, the type that owns the property and the metadata for the property.
  • As per convention make it public static and readonly.
  • The assessors for the property become one liner by getting and setting the dependency property.

 

The dependency object that gets returned by register is used to identify the property.

The metadata can define the default value of the property, callbacks from the receiving property change notification, performing value Coercion.

The Change Notification handler is passed as a part of the metadata. WPF will call this handler anytime the property value changes. Only the property changed directly will go through the set assessor. The changes originating from styles, data binding, triggers, animation will not go through the set assessor. So the callback is useful these changes. So we can write the static callback function as it goes through the static property.

 

Attached Properties

These are not very different from Dependency property. The problem is that C# does not provide any built in syntax for attached properties so we have use RegisterAttached to register an attached property and define the get and set access for the property.

 

Inheritance

Inherited properties are the ones whose value cascades down the visual tree and to all decendents of the target window. So when we apply a property like FontSytle it cascades down the child elements as well. To enable this we need to pass the inherit flag while constructing the metadata. We should avoid callback function along with the inherited properties because it will be called for each and every child element of the visual tree.

 

UIElement and ContentElement

The Visual class derives from DependencyObject and it’s the base class for the everything in the Visual Tree. We cannot derive our class from Visual though. It has functionality which might change in future version and hence is not made public. We can derive from UIElement. Practically UIELement is the base class for all visual elements in the visual tree.

Another class called the ContentElement is the base class for the text based elements like the Paragraph, span, italic, etc.

 

Core and Framework

Visual, UIElement and ContentElement are part of Presentation Core. Framework Element is the baseclass of User Interface elements whereas as ContentElements is the base class for text elements. As you would know WPF is splitted into core rendering services and high level framework services that provide binding, styling and so on. So Framework element is the base class of UI elements and FrameworkContentElement is the base class of text elements. You should know that DependencyObject is neither a FrameworkElement nor FrameworkContentElement type. It lives in WindowsBase dll. This contain WPF types which are not user interface elements.

 

Freezeable & Animatable

The Freezable class also derives from DependencyObject and the base class for brushes, pens, animations, 3D models, etc. In other words it’s the base class that defines the types that define the user interface elements rather than having the behavior themselves. One feature of Freezable elements is that they can be reused and if the value of the element is changed it will be updated at all the places. But this comes with a cost as WPF will have to remember at all the places where this element is used. But if we never want to change it then we can freeze the element. And once frozen the element will throw an exception changing and hence we have saved the cost of remembering the where all the element is used. Freezing is also useful in threading. As we know that DependencyObject supports threading but we can change the element on the thread on which it was created. But freezing helps us created an element on the worker thread and pass it on the UI thread when we are done. Freezing is really effective for large 3D complex models.

Animatable derives from Freezable. All the animation types derive from freezable except the animation object. Most of the freezable types are the things we might want to animate like a Brush’s color or a geometry’s shape. So these things are are valid targets for animation. But we also want to make animation themselves the target of animation. And 2nd order animation is not supported by WPF. So animation are one type of freezable that do not get to be a target of an animation.

 

Any questions. comments & feedback are most welcome.

 

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.

 

 

Hey guys,

Let’s talk about graphics in WPF. We would talk about the WPF graphics architecture followed by vector graphics, bitmaps and videos, WPF resolution independence and effects provided by WPF.

It might seem interesting to you WPF is built on DirectX 3D rendering engine for all its accelerated 3D rendering pipeline and 2D bitmap rendering. This enables WPF to take the advantage of the modern graphics card engines to a large extent through the Media Integration Layer (MIL). MIL being the unmanaged part helps to make use of the directx to huge extent. Also it helps the main .net (WPF) to communicate with the directx.

WPFDirectX

You should note here that the MIL unmanaged API is not public at the moment but its presence effects the public .NET API. These capabilities allow the user to make use of the graphic capabilities of the modern computers hardware. Now it becomes import for you learn these capabilities so that you could get the best performance out of the WPF graphics.

Transforms

One of the major advantages of WPF is its scalability to support higher resolution for higher DPI screens. WPF provides this facility by providing transform capability to all the elements of the Visual Tree. For example if we apply scale transform to an element in the visual tree then the transform will apply to the node and all its children. This is all taken care by the WPF engine internally so that the developer does not have to worry about all that. You do not need to know anything about the GDI32 or GDI+ to get the work done.

WPF Transforms

WPF Transforms

 

There are several other types of transforms as well that can be applied to WPF elements. These include rotate, translation, scaling and shearing. It does not support perspective transform. If you want the perspective transform then you need to use the WPF 3D features. Now if you would use the rotate transform you would notice that the control is not actually rotated but WPF creates a rectangular bound around the control and use the perpetual effect on win32 to show this transform.

As we would see in the image below we have applied a rotate transform onto the combobox.

 

WPF Transform Combobox

WPF Transform Combobox

The transforms that WPF offers are the ones that we can use to affect the 3X3 transform matrix. These transforms are translate, rotate, skew and scale. To use the perspective transform we need to use the WPF 3D features.

Composition and Integration

Another feature in WPF is to integrate images and media to a WPF application. You can have the video content inside any WPF content control including a button. These kinds of things are really difficult to do in previous version of windows applications. In Win32 overlapping controls are not completely support but in WPF you could have overlapping controls and play around with the opacity of each control. The reason WPF can support such graphics is that WPF has much simpler rendering model. WPF follows the painter algorithm to paint the window. So painting a WPF window is like a painting a picture that means the things you paint later will appear on the surface above the ones painted before.

 

WPF Composition and Integration

WPF Composition and Integration

Procedural vs. Declarative

Declarative style is when you tell the computer what you want and let the computer decide on how to achieve that. The best example to see is SQL, we just tell SQL what results we would like and SQL fetches it for us. But this not quite how the user interface programming works, we need to specify some kind of method that we need to specify which will be called when the element is ready to be displayed. As we can see the code below that we have tapped into the code for OnRender method.

 

WPF Procedural

WPF Procedural

Now let’s use this CustomRender element of ours.

 

WPF Procedural

WPF Procedural

Now before we run this application let’s add a trace to the OnRender method and see how many times WPF makes call to OnRender method. What this trace will do is it will print a message onto the debug window whenever this method is hit.

 

WPF Add Trace

WPF Add Trace

Let’s fill in the additional details.

WPF Add Trace

WPF Add Trace

We will notice that OnRender method is called only once. Let’s see if OnRender is called when we transform the element. Add the following code to the code behind file of the RectangleEllipse.xaml.

 

WPF Rectangle

WPF Rectangle

Now when we run the application and get a scale transform on mouse down, we will see that the OnRender method is still not called. So let’s understand what’s happening here. When OnRender is called the drawingcontext will remember what we asked it to render i.e. a rectangle and an ellipse. It will pass this information to the MIL to perform the actual render. What WPF does is prepares the message with the drawing context of needs to be rendered to the MIL and then MIL renders graphics on its own. So we tell WPF to scale the element what WPF does is passes this message with the details that need to be changed onto the MIL to scale the graphic which was passed to the MIL earlier. And MIL uses the copy of the drawing context to rebuild the new image with the transform. The MIL retains the copy of each drawing associated with each node of the Visual tree.

But this is not the way we generally send the instruction to WPF. Mostly we use the declarative syntax and allow WPF the way it wants to display the graphics. We use XAML here instead of C#. The difference between declarative and procedural programming is that in declarative programming we just define the outcome whereas in Procedural we define the steps we need to follow in order to achieve the desired outcome.

 

WPF Declarative XAML

WPF Declarative XAML

It’s difficult to work with procedural approach and is more error prone. We can achieve the same using declarative syntax in C#.

 

WPF Declarative C#

WPF Declarative C#

Primitives vs. Shapes

In the last example we saw a difference between the procedural and declarative code. In the procedural code we typed Rect whereas in the declarative code we typed Rectangle. This actually represents the difference between the presentation core and the presentation framework. The Presentation Core provides a direct wrapper on top of the MIL. This means that the type Presentation Core uses are fairly close to the types MIL works with. These are generally the simple low level primitive types which do not have a lot of information. We cannot exactly identify Rect on the screen as the same rectangle might be used at 20 different places on the screen.

The types we use in the declarative code are much higher level. It will handle events and we can identify the presence of the rectangle exactly on the screen. The higer level types are derived from the Shape base class and have a much deeper set of services. Also these cost more in terms of resources as a rectangle is a much heavier object than rect struct.

 

The reason for this is that WPF has a split between the Core and Framework. So if we do not need the framework services then we do not need to pay the cost for it and work out with the core type. So the reason for using core type is

  • To increase the performance by reducing the resources required by the object.
  • To use the types to which the framework has not provided any wrapper to like the brushes.
  • Do not need high level types.

But most of the time the higher level types are the first and the best choice.

Basic Brushes

Brushes are the core elements and do not have framework wrapper form them.

We have three types of brushes

  • SolidColorBrush – It is the brush which will uniformly paint the surface of an element. We can also add the transparency effect in this brush. To see this action let’s open the WPF project in Blend and add a couple of rectangles to the canvas overlapping each other. Now give different backgrounds to both of them and set the alpha value of the rectangle above as 50% and we would see something like below.

 

WPF Solid Color Brush

WPF Solid Color Brush

  • LinearGradientBrush – Now let’s add another rectangle and select GradientBrush in the Editor.

 

WPF Linear Gradient Brush

WPF Linear Gradient Brush

Now let’s click the gradient bar to add new stops to add the colors for the gradient brush.

 

WPF Linear Gradient Brush

WPF Linear Gradient Brush

We can also select the brush transform tool to select the direction of gradient.

 

WPF Linear Gradient Brush

WPF Linear Gradient Brush

Now let’s have a look at the xaml for this.

 

WPF Linear Gradient Brush

WPF Linear Gradient Brush

  • RadialGradientBrush – Now when we selected the gradient brush the default was LinearGradientBrush but we can also select a RadialGradientBrush.

 

WPF Radial Gradient Brush

WPF Radial Gradient Brush

Geometries

WPF represents shapes as geometry objects. Geometry is an abstract base class and the most powerful geometry is path Geometry. This defines shapes as a series of figures whose outlines are defined as a series of LineSegment. Let’s a geometry is action. When add the following code to the xaml we do not see a shape but some cryptic text. I will tell you what happened here. Geomerty is path of core API and so they are not allowed in a UI tree directly. We need to pass the geometry to a drawing object or shapes. So whats happened here is that UserControl has figured out that PathGeometry is not a UI element so it has called the ToString on the geometry and displayed the result. SO render this geometry we need to put it into a suitable shape.

 

WPF Geometry

WPF Geometry

Let’s put this geometry into a path and we will be able to see our geometry.

 

WPF Geometry

WPF Geometry

So all the shapes work in a way that they override the OnRender method under the hood and pass the information to the MIL for display. We can tweak the numbers to change the shape. Now let’s see how the multi figure PathGeometry will be displayed. Let’s add a second figure which will remain inside the first figure. We will see something like below.

WPF Geometry

WPF Geometry

So we see a hole in the object which is actually not a hole but WPF does this. When the figures overlap they cancel each other out. WPF counts the number of figures at any point and if the number is odd it fills in the shape and if the number is even WPF leaves it unfilled.

 

WPF Geometry

WPF Geometry

Simple Geometries

The other types of geometries are

  • LineGeometry
  • RectangleGeometry
  • EllipseGeometry

GeometryGroup

Another geometry class is GeometryGroup. It helps us combine multiple geometries into single geometry where each geometry has its own place. Let’s see this on action.

 

WPF Geometry Group

WPF Geometry Group

Path Syntax

When we create a path using the Pen tool in expression blend we will not see anything like PathGeometry in the xaml produced. We will something like shown below. The Data starts with M which means move to this point start the path. Then we have C which is and has four co-ordinates for itself. We keep moving further this way and at the end we will see z which means the end.

 

WPF Path

WPF Path

We can use thin inside any PathGeometry or the data property of the Path. When we represent the geometry as a string it is not represented as a PathGeometry but a StreamGeometry. It does not need to contain the Figures objects.

Drawings

As we saw in the previous section that we had to put the geometry inside a path so that it is rendered properly. But as you might know that Path is a framework element and there are cost involved with its rendering. We not necessarily need a framework element to display our element. Instead we can use WPF drawing structure to display geometries. Drawing is a collection of drawing objects. We can wrap all the drawing objects that MIL can display in a DrawingGroup and using this we can paint geometries, bitmaps, text and videos. The MIL retains the visual representation of all the elements all all nodes of the visual tree so that it can display updates as well and the representation it uses is drawing. So we are talking to MIL in its own language. So this makes drawing the efficient representation in WPF graphics. We do not need to write code to create these drawing as it can be done in XAML. Like geometry dwaring is just a description and does not know how to render itself. So we need to put it inside a DrawingVisual to render it. Let’s see this code. DrawingGroup is at the root of a drawing. DrawingGroup acts as a container for a series of DrawingObjects. We need add this DrawingGroup to the source of an image drawing.

 

WPF Drawings

WPF Drawings

Instead of setting this ImageSource of the image we can set GridBackground of the Grid to DrawingBrush will get the similar effect. This is really good because if we are a lot of framework (above 5000) then we can see a significant drop in the performance. Drawing elements are really useful as they reduce the framework element count and improving the performance of the WPF application. But have to pay cost for using the drawing as from the event handling perspective the whole drawing seems to be one element. Drawings behave like bitmap but these are vector.

Composite Brushes

The drawing brushes that we saw are an example of Composite drawing brushes. They itself contain brushes so we can nested inside another brush and so on. WPF offers another brush named VisualBrush. So rather than using a drawing we can use any VisualTree or Sub Tree as a Visual Brush. Let’ see this in action. We have the fill of the grid to a visual brush. The contents of the grid are a brush but the contents are not interactive.

WPF Composite Brush

WPF Composite Brush

 

TileBrush

All the composite brushes ImageBrush, DrawingBrush and VisualBrush share a base class called a TileBrush. This base class provides properties as below

  • Stretch – This property determines how the content would scale on render. It has values like Fill, None,Uniform,UniformToFill.
  • Viewbox – The Viewbox specifies the source area of interest in an image. So if want only a part if the image we can use as shown below. We can also specify the ViewboxUnits as RelativeToBouindingBox or Absolute pixels. So a Viewbox defines the source material to be used as a brush material. It defaults to relative units.

 

WPF Viewbox

WPF Viewbox

  • Viewport – Viewport defines as to where the source material is projected onto the target. It also defaults to relative units.

 

WPF Viewport

WPF Viewport

Transforms

WPF supports transforms on any part of the visual tree. The transforms supported by Visual Tree are:

  • ScaleTransform
  • TranslateTransform
  • RotateTransform
  • SkewTransform
  • TransformGroup
  • MatrixTransform

We can use them individually or combine them in a transform group. There are two ways in which we can apply transform to a UI element.

  • RenderTransform – This will affect only on the element which it is applied and WPF makes no attempt to reform the layout to accommodate the change in the element.

 

WPF Render Transform

WPF Render Transform

  • LayoutTransform – This will affect the whole visual tree to accommodate the change in the user interface.

 

WPF Layout Transform

WPF Layout Transform

Transform is also a core type and we can apply transform to a drawing or geometry. Also we can apply transform to the brushes as well.

Clipping and OpacityMask

These are the effect that can be applied to any element in the visual tree. We can use geometry to clip any element or we can apply an opacity mask. When we clip an element then anything which is not inside the geometry becomes invisible. WPF anti aliases the border to provide a smooth look. So anything in a clip is clipped with sharp abrupt edge whereas while using the opacity mask we modulate the opacity. Let’s see this in action.

 

WPF Clip

WPF Clip

But this clipping comes with a cost. When we apply clip to a control then WPF renders the entire element into an off screen buffer and then renders the clip result into the main screen. So each element we apply clip to needs an additional buffer.

 

WPF Opacity

WPF Opacity

The same rendering as clip applies to opacity mask as well. It could be even worse as it might end up switching from Hardware acceleration to Software acceleration which might be catastrophic.

Bitmap Effects

WPF also offers a few Bitmap processing effects as well and these can be applied to any element in the visual tree.

  • DropShadowBitmapEffect
  • BlurBitmapEffect
  • EmbossBitmapEffect
  • BevelBitmapEffect
  • OuterGlowBitmapEffect

We can apply multiple effects by using BitmapEffectGroup. In the image below we see a couple of these effects.

 

WPF Bitmap Effect

WPF Bitmap Effect

Animation

In this section we will have a quick look at the services provided by the animation system for dynamic objects. As we can see in the image below we need to specify the trigger which will tell when to start the animation. Here we have an event trigger which will start the animation when this Rectangle.Loaded event occurs. Then we have defined that BeginStoryboard will occur when the specified event is triggered. We can also pause or stop an animation. A storyboard is an orchestration of the steps that the animation will go through. For the demo purpose I have included only one step here. We have also specified the property the animation will change. So the animation type should be corresponding to the specified property. Like below the width property is of type double so we have used DoubleAnimation. We have specified the initial and final values. Also it has the time for the animation will run.

 

WPF Animation

WPF Animation

3D

WPF allows us to incorporate 3d content into our WPF application. The Viewport3D element hosts a 3D model into our WPF application. As the layout only knows about the 2D content so for the layout Viewport is just a rectangle that displays some content. As see in the image below we need to include a 3D camera and a 3D Model will have at least one light and a shape. Generally we will export this 3D model from a 3D design tool. But we can the code below to the xaml file and see how it would look.

 

WPF 3D

WPF 3D

And this how it will appear

WPF 3D

WPF 3D

The code for this post can be found here.

Any questions, comments and feedback are most welcome.

 

Master Pages

The most important thing to have in the website is a consistent look and feel for the whole website and it involves have a similar colour scheme and similar structure for all the pages on the website. Generally the pages in the website are structured in a way that they have a fixed header, fixed side navigation panels, fixed footer and dynamic centre content. The goal is always not replicate the code in the header, footer and side navigation panels. So we need to have a mechanism by which we can place this code in separate file and when we change those vales the changes should be propagated to all the pages.

Master page in ASP.NET provides this facility. So the way it works is that we have a single top level file named with extension as .master. This master page will contain the overall look and feel of the page. We can define our header, footer and panels in the master page file and we also place a placeholder position where the content of the page will be placed. Then we build up the content pages. These pages will be standard ASP.NET pages wired up with the master page and when they render their content then their content is surrounded with the header, footer and panels from the master page. There can be any number of the master page, content place holders, etc.

 

Master Pages ASP.NET

Master Pages ASP.NET

The actual code for the master page and content page will look like something below. The master pager will end with the .master extention and it will have the similar attributes that the Page Directive does like the Language. Then there will be top level layout and then we put one or more ContentPlaceHolder and this is where the ASP.NET pages will have their regular content.

The Page will have a link to the master page and then it will have a content control which is linked to the ContentPlaceHolder of the master page. Any content specified will be injected into the ContentPlaceHolder.

<!-- MasterPage.master -->
<%@ Master Language="C#" %>
<html>
<body>
    <form runat="server">
        <h1>My Common Header</h1>
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server" />
    </form>
</body>
</html>

 

<!-- Page1.aspx -->
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </asp:Content>

 

Now let’s have a look at the actual code in Visual Studio. So lets create a new asp.net website and delete all the files and folder in it except Default.aspx and Web.Config from the solution explorer. Now add a MasterPage to the site named SiteTemplate.master and add the following code to it. This master page will have the header, footer and the maincontentplaceholder for the site.

 

Master Pages ASP.NET

Master Pages ASP.NET

Add the following content to the Default.aspx page. At the top of the page we add a reference to the MasterPage. And then we place a Content control wired up to the ContentPlaceHolder of the MasterPage and add the a couple of calendar controls into it.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now add two more pages to the website named Page1.aspx and Page2.aspx and add the following code to them. Similar to the default.aspx we have added a reference to the MasterPage which will govern the header, footer and side panel of the website and the content control that we have added will be the content that will be different on different pages.

 

Master Pages ASP.NET

Master Pages ASP.NET

Let’s now have a look as to how the master page injects content into the content pages. We should think it in a way that the content page is the endpoint and it is responsible for dispatching the content and the master page is going to be injected as the child control in the hierarchy of the content page. The other important thing to know is that the actual content that is added to the content page is dropped into the ContentPlaceHolder inside the hierarchy in the master page. But in the end the content is rendered as the normal html content. We can a have a look at the hierarchy in the image below.

 

Master Pages ASP.NET

Master Pages ASP.NET

When you open the default.aspx in the Design mode then you would notice that the design interface of Visual studio will allow you to edit on the content part of the page and the remaining part of you page which is derived from master is not editable.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now let see the relationship between the master page and the content with regards to the control hierarchy. So let’s enable the trace at default.aspx.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now let’s run the site and the trace part looks something like below.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now as the master page is defining the content of the page hence we need to know a few things for our pages to look the way we want them to look like.

  • Title attribute of the pages – This is really important because the title attribute is being defined as the part of the master page and that is where we need to place the title but we need have a distinct title for different pages. It’s really staring forward to do while using master page because the head content is marked as runat server and the title attribute takes it value from the content page title. So we could have the default title of the site in the mater page as shown below.

 

Master Pages ASP.NET

Master Pages ASP.NET

And then we can set the Title of the content pages which will overwrite the default title in the master page.

 

Master Pages ASP.NET

Master Pages ASP.NET

  • Now on some of the page we might want to hide our side panel so what we need to do is add a panel and add the code for the left pane inside it

 

Master Pages ASP.NET

Master Pages ASP.NET

Now let’s add a property to the MasterPage using which we will use to set the visibility of the Left Panel.

 

Master Pages ASP.NET

Master Pages ASP.NET

 

Now we access this property for hiding and showing the visibility of the left pane by accessing the master property for this page in the pageload method.

 

Master Pages ASP.NET

Master Pages ASP.NET

Another way to do this is to use the VirtualPath property in the MasterType directive and set it to the masterpage of the site.

 

Master Pages ASP.NET

Master Pages ASP.NET

Now as we have specified the MasterType at the masterpage so we do not need to typecast it as the SiteTemplate and we can simply directly access the Master Page.

 

Master Pages ASP.NET

Master Pages ASP.NET

  • We can set the masterpage of the content page in the code as well by setting the Page.MasterPageFile but for it work without exception we need to call it in Page_PreInit.

Nested Master Pages

It is perfectly alright to have a MasterPage for the MasterPage as well. So as you can see in the image below we have defined the MasterPageFile attribute in the Master directive of a master page. The reason to do this is to add an addition level of layout. Also you need to see that in the child master page we need to specify the content in the ContentControl just like the content page. But we need to be careful that to access the ContentPlaceHolder of the root master page then we need to redeclare it in the child masterpage.

<!-- SiteTemplate.master -->

<%@ Master Language="C#" %>
<html>

<body>
<form runat="server"> 
<h1>common header</hl> 
<asp: ContentPIaceHoIder" runat="server" />
<!-- SecondaryTempIate.master -->

<%@ Master Language="C#" MasterpageFile="~/SiteTemplate.master" %> 
<asp: ContentPlaceholderID="mainContentPlaceholder" runat="server"> 
<table><tr><td>
<asp:ContentPlaceholder ID="leftContentPlaceholder" runat="server"  />

</td><td>

<asp:ContentPlaceholder ID="rightContentPlaceholder" runat="server"  />

</tr></table>
</asp :Content>

 

Let’s see this in action by creating a new MasterPage

 

Nested Master Pages ASP.NET

Nested Master Pages ASP.NET

Let’s add a Content Panel for the head content so that if someone wants to access the head container in the root page then they can do that. Also let’s add a fieldset in the mainContentPlaceHolder with a legend.

 

Nested Master Pages ASP.NET

Nested Master Pages ASP.NET

Now let’s add a Page3.aspx which will use this SecondaryTemplate.master as the masterpage and add its content in the content place holder.

 

Nested Master Pages ASP.NET

Nested Master Pages ASP.NET

Themes in ASP.NET

Themes are a useful way to give a consistent look and feel to the controls throughout the application. It is a consolidation of UI elements by the use of stylesheets, skin files, images,etc. Let’s see how themes can be added and used in the application. So Theme is a directory in the application level directory in the App_Themes directory and it can contain zero or more .css files and all .css files are implicitly referenced.

 

Themes in ASP.NET

Themes in ASP.NET

This will add two directories added by this option.

Themes in ASP.NET

Themes in ASP.NET

 

Let’s add a stylesheet to this directory. And add the code shown below to it.

 

Themes in ASP.NET

Themes in ASP.NET

Themes in ASP.NET

Themes in ASP.NET

Now let’s add a new page which does not uses any maasterpage and add the following code to it.

 

Themes in ASP.NET

Themes in ASP.NET

 

When we run our application we will see that the textboxes will have the colo as specified in our theme css file.

The Theme folder may also contain one or more .skin files. A skin file will contain control declarations with default attributes. This will provide a consistent look and feel for the controls that use that skin. We did not put the ID against the controls because we do not want it to apply. We can also put the  ID against the controls so that the controls that indivisually want to use that style can do that by referring the ID.

<asp:button runat="server" borderStyle="Solid" borderwidth="2px" bordercolor="#66ff66" backcolor="#99ffff" />

<asp:calendar runat="server" borderStyle="Solid" borderwidth="2px" bordercolor="#66ff66" backcolor="#99ffff" />

 

Also the theme folder may contain zero or more subdirectories with resources like images or scripts. So all the resources used in  the theme could be placed here.

Let’s see this in action. Let’s add a new skin file in our theme1.

 

Skin File in ASP.NET

Skin File in ASP.NET

Now add the code to this theme file as shown in the image below. The first thing that we need to do is add SkinID to the controls in the MyTheme.skin, if we want to use these control styles on a per control basis.

 

Skin File in ASP.NET

Skin File in ASP.NET

Now let’s go back to MyThemedPage.aspx and use this style. Now as we have applied the Theme1 to the MyThemedPage.aspx the textboxes there will automatically pickup the style of the textbox which has no SkinID. If we want to use a style that has a skinid then you would need to add that skinid to the control we want to apply the style to. So the textbox1 will have the cssclass foo applied to it will be foo and textbox2 will have the cssclass bar applied to it.

A very simple thing to do is replicate our theme. We can just copy the Theme1 and paste it into the app_Themes folder.

 

Themes in ASP.NET

Themes in ASP.NET

We can then edit the css file in this skin very easily and use it as it already has the same structure and the class named and skin id are all the same and we change or add or delete styles in the css file.

 

Themes in ASP.NET

Themes in ASP.NET

Now let’s add a calendar control to the MyThemedPage.aspx and apply professional1 theme to it. It would look something like below as shown.

 

Themes in ASP.NET

Themes in ASP.NET

Now go back to the Source mode. We will see something like as shown below.

Themes in ASP.NET

Themes in ASP.NET

We will copy that calendar code and paste it in the Theme1àMyTheme.skin and remID and add a SkinID as professional.

 

Themes in ASP.NET

Themes in ASP.NET

And now we could use that in our themed page.

 

Themes in ASP.NET

Themes in ASP.NET

Let’s add a images folder and add an image to it. Then we would add a asp:Image control and reference that image into it.

 

Themes in ASP.NET

Themes in ASP.NET

Now we will utilize this image in our MyThemedPage folder.

 

Themes in ASP.NET

Themes in ASP.NET

We would see something like bleow.

 

Themes in ASP.NET

Themes in ASP.NET

What we did before was applied the theme to the page level and now what I am going to do is apply that theme to all the pages in my site by specifying the same in the web.config file. This will impliclitly include a reference to the theme file into all the pages of my site.

 

Themes in ASP.NET

Themes in ASP.NET

Now let’s see how the theme actually works. The way we saw to set the theme on the web.config sets the theme globally and if do not want that theme to certain pages we can override by specify a different theme for that page in the Page directive of that page.

 

Themes in ASP.NET

Themes in ASP.NET

We can also set up the themes programmatically. We need to set the theme in the PreInit event handler of the page.

 

Themes in ASP.NET

Themes in ASP.NET

We can also set the themes globally dynamically.

  • We could subscribe to PreRequestHandlerExecute and wireup a PreInit handler on the fly.
  • Then set the theme in the PrInit handler and that will apply the changes to all the pages.
  • This can be stored in Profile, session, config,etc.
  • Same technique works for master pages as well.
<%-- File:Global.asax --%>
<%@ Application Language="C#" %>
<script runat="server">
void Application_PreRequestHandlerExecute(object src, EventArgs e) {
    Page p = this.Context.Handler as Page;
    if(p!=null)
        p.PreInit += new EventHandler(page_PreInit);
}

void page_PreInit(object sender, EventArgs e) {
    Page p = this.Context.Handler as Page;
    if(p!=null)
        p.Theme = (string)Context.Profile["theme"];
}
</script>

 

Navigation Controls

In ASP.NET 2.0 3 new site navigation controls were introduced.

  • TreeView
  • Menu
  • SiteMapPath

All these 3 controls can use SiteMapProvider which derives its default data source from web.sitemap and it is a standard xml format for page.navigation. Let’s see how this works. Let’s add a sitemap to our site

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

Let us add the sitemapnodes to it hierarchal.

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

Now let’s go back to the MasterPage and go to the Navigation in the Toolbox and use the TreeView , menu and sitemappath.

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET
Navigation Controls in ASP.NET

This is how it looks

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

The image below shows the hierarchy of the navigation controls.

 

Navigation Controls in ASP.NET

Navigation Controls in ASP.NET

The Code for this post is available here.

 

Any questions, comments and feedback is most welcome…

 

HTML Controls

HTML Controls are collection of the server side controls that give the server side representation of the client side HTML elements. We can create a server side object by giving any client side HTML element with the attribute of runat=”server” and giving it an identifier. This is a very convenient way of manipulating server side elements without messing up the markup. It is useful at places where you have already existing HTML elements in you code and you do not want to completely replace them with the server side web controls then we can set up the marking for some of the controls to runat server.

Let’s have a look at this in action. Let’s open the exiting folder that contains the files HelloWorldCodeBehind.aspx and HelloWorldCodeBehind.aspx.cs as a website in Visual Studio

 

HTML Controls ASP.NET
HTML Controls ASP.NET

It would look something like below.

 

HTML Controls ASP.NET
HTML Controls ASP.NET

What we will see here is how to use an HTML server side control to get rid of the inline markup of GetType. The first way we can do this is go the h3 element and give it the runat server attribute and an id. Also we will remove the GetType call and replace it with xxxxxxxx to indicate that this value will be updated.

 

HTML Controls ASP.NET
HTML Controls ASP.NET

Now let’s go to the code behind. We will tap the load event and do what we were doing in the aspx. When we add the attribute runat server then we get access to that type in our server side code.

HTML Controls ASP.NET
HTML Controls ASP.NET

 

Web Controls

Another category of the server side controls is WebControls and its present in the System.Web.UI.WebControls namespace. These are generally used over there HTML counter parts as these are listed as the standard controls in the toolbox. They are more convenient to work with because they have more consistent property names. So once you know how to use one control you can easily use the other which is not the same in the case of HTML controls. Many of these Web Controls are replacement of the HTML controls and other are more complex.

Let’s see these web controls in code. So we have already used BulletedList which is a webcontrol that renders as an unordered list. So let’s remove the Response.Write and replace it with a label.

 

Web Controls ASP.NET
Web Controls ASP.NET

Now we will add the logic to display the total number of items in the label inside the Load Event in the server side code.

 

Web Controls ASP.NET
Web Controls ASP.NET

Let’s add a calendar and display it on the page.

Web Controls ASP.NET
Web Controls ASP.NET

 

When we view the source of the displayed aspx page we will not see a control but a table with all the elements defined in it.

 

Web Controls ASP.NET
Web Controls ASP.NET

Control State Management

One of the most important things in Control State Management in ASP.NET is that they maintain their states even during the post backs. So sequence is as below:

  • The initial get request to a page creates the server side controls with their default values specified on the initial form.
  • Then if the user clicks on an element that generates a post request onto the same page then this would generate the POST message that would be handled in the server. Then when the server creates the page then the page creates the server side controls with the values in the POST body of the request that came back.
  • So the changes that are made by the client in the controls will be reflected in the server side controls and consequently the response for page render.

The flow of the Web Form Client interaction is shown in the image below.

 

Control State Management ASP.NET
Control State Management ASP.NET

Let’s see that in action. Let’s create a new page named State.aspx and add the following code to it.

 

Control State Management ASP.NET
Control State Management ASP.NET

 

Control State Management ASP.NET
Control State Management ASP.NET

When we run this page we can see state retention in action.

There are several implications of State Retention as well.

  • There is no need to re initialize state in controls when we are processing post back requests.
  • Can’t do cross page posting by default.
  • Controls that are not intrinsically included in a POST back will not retain their state by default and we will have to request their state propagation via hidden fields.

Let’s see this in action by optimizing our Load event code. We will check for the IsPostBack property of the page to determine whether this load is a post back or not. If it is not then only we assign states to the controls otherwise the state will be retained.

 

Control State Management ASP.NET
Control State Management ASP.NET

ViewState

The model of state retention for server side controls is pretty simple when we look at the input controls that are sent back as part of the post back. Now we need to see how the controls that do not contribute to the POST body will maintain their states. These elements includes div, span, li, p, table, etc. The answer is ViewState. ViewState is the additional hidden input element which is generated when each page is rendered and it is used by controls to insert additional state during post back.

The best way to see this is in code. Let’s create another Form named ViewState and add the following code to it.

 

ViewState ASP.NET
ViewState ASP.NET

So whenever we click on the button a post back happens but the state of the label is still persisting its state.

ViewState is persisted as a serialized tuple-based data structre and encoded as a base64 string. So we can use any base64 decoder to decode the ViewState. We can download a ViewState Decoderfrom http://tinyurl.com/4dn377. It would look something like below.

 

ViewState ASP.NET
ViewState ASP.NET

Disabling ViewState

ViewState is a perfectly useful way to propagate requests while dealing with small controls that have fairly less ViewState associated with them but large amount of ViewState on controls like databound controls we must turn it off. There are two way in which we can disable the ViewSate.

  • Set EnableViewState=”False” in the page directive. This will disable the ViewState for the entire page.
  • Set EnableViewState=”False” on the individual controls. You can identify thecontrols that does not require ViewSate and set this attribute and we should do this on the controls that have a significant ViewState usage.

This will reduce the amount of data in the request that goes back and forth.

Change Notification Events

In the previous section we have seen when and where to disable the ViewState. In this section we will see where we should not disable ViewState.

  • Do not disable ViewState on Server-Side controls that issue change notifications events based on ViewState.
    • Because the Prior Value is stored in the ViewState to keep track of the changes.
    • During subsequent POST requests the current and the cached values are compared and if they are different then a change notification is issued.

EventTarget and EventArgument Fields

There is another method to find out which server side control actually initiated the server side request and this has an EventTarget field and an EventArgument field. Some input elements like Button, imagebutton, etc already send data in the POST body that can help us identify the sender. But there are some controls that do not use standard postback mechanisms. For example the change notification in thelinkbutton, drop down list when autopostback=”true”. This does not have any data included in the POST that will help us identify that it is the control that initiated the postback. That is why there are these 2 other fields which helps us identify as to which control issued the postback. So the EventTarget Hidden field stores the control id that issued the event and the EventArgument Hidden Field will store any parameters sent for the event.

ControlState

ControlState is a feature which was added with release 2.0 of ASP.NET. The idea behind ControlState is to give the developer another repository for saving the state apart from the ViewState that cannot be disabled. This was to fix the issue that was faced in the previous version when the ViewState for certain controls like GridView, etc was disabled then the control did not work properly. So now the user has the option to distinguish the behaviour state by placing it into the controlstate and by placing simple data into viewstate. ControlState is not a separate hidden field but it is an additional collection of state data appended to the end of ViewState. So we can now turn off the view state for the controls without any issues. So all of the newer data-bound controls in ASP.NET makes use of the Control State.

Explicit Use of ViewState

ViewState can also be used as the means to store client-specific state which will retained across the POST requests to the same page. But we need to make sure that the types are serializable. These are directly accessible from the Page.ViewState property on the page and it returns the collection of the ViewState properties.

So let’s see how we can make exclusive use of the ViewState property. Add a new WebForm to our existing website and add a listbox in the aspx file. Also lets add the label to the aspx.

 

ViewState ASP.NET
ViewState ASP.NET

Now let’s add a handler for selectionchanged event of the ListBox. We will add the logic that whenever the user clicks on the listbx we will update the label by storing the count in the ViewState.

 

ViewState ASP.NET
ViewState ASP.NET

The code for this Post can be found here.

Any questions, comments and feedback are most welcome.