Saturday, June 30, 2007

How to Bind an Adorner to an Element?

To bind an adorner to a particular UIElement, follow these steps:

Call the static method GetAdornerLayer to get an AdornerLayer object for the UIElement to be adorned. GetAdornerLayer walks up the visual tree, starting at the specified UIElement, and returns the first adorner layer it finds. (If no adorner layers are found, the method returns null.)
Call the Add method to bind the adorner to the target UIElement.
The following example binds a SimpleCircleAdorner (shown above) to a TextBox named myTextBox.

myAdornerLayer = AdornerLayer.GetAdornerLayer(myTextBox);
myAdornerLayer.Add(new SimpleCircleAdorner(myTextBox));

Have a fun with WPF programming. Enjoy......!

Using Extensible Application Markup Language (XAML) to bind an adorner to another element is currently not supported.

Monday, June 25, 2007

What is this "Content Model" in WPF?.

WPF's content model is usually described as either rich or flexible - but what does the term "content model" mean in this context? Legacy windows programming platforms (MFC,ATL,VB6,Windows Forms etc) had many different types of controls that could be added to UI - buttons, labels, pictures, text boxes, lists etc. Each one of these types of controls usually had a fairly fixed set of things they could display - buttons, labels and text boxes could contain text, picture controls could contain images, lists contained a number of list items, each of which in turn contained text. To go outside this usually involved some effort - either writing a control from scratch that could contain a different type of content, or taking over part of the rendering process and performing some "owner drawing", which was often somewhat involved.

In contrast WPF doesn't make nearly as many assumptions about the types of content you would like to display inside a given control. Content of different kinds can be nested freely inside other elements. The following XAML snippet defines a button. Inside the button is contained some text, an ellipse, a text box and a combo box. Inside the combo box is more text and another ellipse.


Although this example is not the type of functionality that has been required for in any application that I have ever written, it is this flexible way that content can be nested and composed that underpins many of the powerful things that can be done in WPF.

Have fun with WPF programming... Enjoy..

Friday, May 4, 2007

Resources In WPF

we can reuse objects in XAML by first defining them as Resources .. this is not a .net normal resources. Because that will in the resources file and we can use for storing images , text , etc... and accessed with Uri object. and also it will shipped with executable files or .dll files. Here we are going to write resources inside of XAML or (sometimes in C# code). It will associated with an element or control, page or Window in the application.

Format of Resources:

<SomeType x:Key=”keyname” ...> </SomeType>

Type of Resources :
  • Static Resources
  • Dynamic Resources

Static Resources

XAML elements can reference the resources using the key using markup extension. The particular markup extension you use with resources is named StaticResource.

<StackPanel xmlns="" xmlns:x="" xmlns:s="clr-namespace:System;assembly=mscorlib">
<s:Double x:Key="fontsizeLarge">18.7 </s:Double>
<s:Double x:Key="fontsizeSmall"> 14.7 </s:Double>
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Margin="24">
<StaticResource ResourceKey="fontsizeLarge" />
Button with large FontSize
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Margin="24" FontSize="{StaticResource fontsizeSmall}" >
Button with small FontSize </Button>

Here fontsizeSmall and fontsizeLarge is the static resources. And we have created that resources in element stackpanel. So we can use that resources only child of stackpanel. In case if we declared that resources in window section means we can use anywhere in the single source code. That means insidea of window element.method of accessing static resources .

<Button.FontSize> <StaticResource ResourceKey=”fontsizeLarge”>
FontSize=”{StaticResource fontsizeLarge}”


Forward reference is not allowed in resource reference.We can define control or element as a resource. But we cant use twice. because it will create only one instance.

Creating resources using C# code.
elementname.Resource.Add(“resource name”,value);

Finding Resources

Application Resources

we can define resources in the Application file . And we can access those resources from anywhere in the application. For that we need create resources under MyApp.xaml file which is created by the VisulaStudio.


XAML defines a markup extension named x:Static specifically to reference static properties of fields.It also works with enumeration members.

Example :
some static property from a class named MyClass.

<x:Static Member=”MyClass:PropertyName” />

Dynamic Resource

With StaticResource the key is used to access the object once and the object is retained . When we use the DynamicResource the key is retained and the object is accessed when its needed. The primary purpose of DynamicResource is to access system resources such as colors.

if we want share multiple resources among multiple applications. We can use resource dictionary.

Example: SampleResource1.xaml

<ResourceDictionary xmlns="" xmlns:x="">;
<LinearGradientBrush x:Key="brushLinear">
<GradientStop Color="Pink" Offset="0" />
<GradientStop Color="Aqua" Offset="1" />
</LinearGradientBrush.GradientStops> </LinearGradientBrush>


<ResourceDictionary xmlns="" xmlns:x="">;
<RadialGradientBrush x:Key="brushRadial"> <RadialGradientBrush.GradientStops>
<GradientStop Color="Pink" Offset="0" />
<GradientStop Color="Aqua" Offset="1" />

MyApp.xaml(Application file)

<Application xmlns="" StartupUri="UseCommonResourcesWindow.xaml">
<ResourceDictionary Source="MyResources1.xaml" />
<ResourceDictionary Source="MyResources2.xaml" /> </ResourceDictionary.MergedDictionaries>

we can access the resources like this .

<Window xmlns="" Title="Use Common Resources" Background="{StaticResource brushLinear}">
<Button FontSize="96pt" HorizontalAlignment="Center" VerticalAlignment="Center" Background="{StaticResource brushRadial}">

Enjoy!!!!!!!!!! If you have a question or you cant get anything in this feel free to comment. I will try to give you as soon as possible.

Tuesday, May 1, 2007

XML DataBinding In WPF

If you have comments, questions or ideas regarding this post content please leave as a comment.

XML DataBinding concept is used to retrieve the data from XML file using XmlDataProvider in XAML language. Windows Presentation Foundation makes it possible to create user interfaces that use data binding wholly in an XML-based markup. When working with XAML we can use the XmlDataProvider object to retrieve XML data and provide it to controls.

Format for Accessing XMLData

XMLDataProvider :

With an XmlDataProvider, the underlying data that can be accessed through data binding in your application can be any tree of XML nodes. In other words, an XmlDataProvider provides a convenient way to use any tree of XML nodes as a binding source. First, we create a XmlDataProvider that will retrieve data asynchronously from the given address and create the data collection with XPath.

XPath :

The XPath properties in WPF are handled by the XmlNode. SelectNodes method. You can modify the XPath queries to get different results. Here are some examples for the XPath query.

  • XPath="Book[1]" - will return the first book element ("XML in Action"). Note that XPath indexes are based on 1, not 0.
  • XPath="Book[@*]" - will return all book elements with any attributes.
  • XPath="Book[last()-1]" - will return the second to last book element ("Introducing Microsoft .NET").
  • XPath="*[position()>3]" - will return all of the book elements except for the first 3.
When you run an XPath query, it returns an XmlNode or a list of XmlNodes. XmlNode is a common language runtime (CLR) object, which means you can use the Path property to bind to the common language runtime (CLR) properties.

Source :

We can specify the xml file source address in source attribute.
<XmlDataProvider x:Key="BookData" Source="http://MyUrl" Xpath="Books"/>

Example 1:
This sample will help you to get data from external XML file named as BookData.xml and binded with listbox.


<Books xmlns="">
<Book ISBN="0-7356-0562-9" Stock="in">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
<Book ISBN="0-7356-1370-2" Stock="in">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
<Book ISBN="0-7356-1288-9" Stock="out">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
<Book ISBN="0-7356-1377-X" Stock="in">
<Title>Introducing Microsoft .NET</Title>
<Summary>Overview of .NET Technology</Summary>
<Book ISBN="0-7356-1448-2" Stock="out">
<Title>Microsoft C# Language Specifications</Title>
<Summary>The C# language definition</Summary>


<StackPanel xmlns="" xmlns:x="" Width="410" Height="350" Background="White">
<XmlDataProvider x:Key="BookData" Source="bookdata.xml" XPath="Books"/>

<DataTemplate x:Key="BookDataTemplate">
<TextBlock FontSize="12" Foreground="White">
<Binding XPath="Summary"/>
<TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center">Data From XML</TextBlock>
<ListBox Width="200" Height="300" Background="SteelBlue" ItemsSource="{Binding Source={StaticResource BookData}, XPath=Book}" ItemTemplate="{StaticResource BookDataTemplate}"/>

Note :
You can put the Xml file in same location of xaml file. If you have external path means you should specify the path of xml file in source(Ex : Source ="data\bookdata.xml" attribute of XmlDataProvider tag.

Example 2:

This sample will help you to embed directly as an XML data island within the Resources :
In the following example, the data is embedded directly as an XML data island within the Resources section. An XML data island must be wrapped in <x:XData> tags and always have a single root node, which is Inventory in this example.

<StackPanel xmlns="" xmlns:x="" Background="White">
<XmlDataProvider x:Key="InventoryData" XPath="Inventory/Books">
<Inventory xmlns="">
<Book ISBN="0-7356-0562-9" Stock="in" Number="9">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
<Book ISBN="0-7356-1370-2" Stock="in" Number="8">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
<Book ISBN="0-7356-1288-9" Stock="out" Number="7">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
<Book ISBN="0-7356-1377-X" Stock="in" Number="5">
<Title>Introducing Microsoft .NET</Title>
<Summary>Overview of .NET Technology</Summary>
<Book ISBN="0-7356-1448-2" Stock="out" Number="4">
<Title>Microsoft C# Language Specifications</Title>
<Summary>The C# language definition</Summary>
<CD Stock="in" Number="3">
<Title>Classical Collection</Title>
<Summary>Classical Music</Summary>
<CD Stock="out" Number="9">
<Title>Jazz Collection</Title>
<Summary>Jazz Music</Summary>

<TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center">XML Data Source Sample</TextBlock>
<ListBox Width="400" Height="300" Background="SteelBlue">
<Binding Source="{StaticResource InventoryData}" XPath="*[@Stock='out'] *[@Number>=8 or @Number=3]"/>
<!--Alternatively, you can do the following. -->
<!--<ListBox Width="400" Height="300" Background="Honeydew" ItemsSource="{Binding Source={StaticResource InventoryData}, XPath=*[@Stock\=\'out\'] *[@Number>\=8 or @Number\=3]}">-->

<TextBlock FontSize="12" Foreground="Red"> <TextBlock.Text>
<Binding XPath="Title"/>

Sunday, April 29, 2007

What is the future of WPF and XAML over other technologies and how may I benefitted from using these two?.

User interfaces are an important part of most Windows applications. No matter how much software evolves, traditional menu-driven GUIs are here to stay for some more time. Similarly, the need to display video, run animations, use 2/3D graphics, and work with different document formats also cannot be superseded. And all of this must be possible whether the application is a stand-alone desktop client or is accessed through a Web browser.

So far, all of these aspects of the user interface have been provided in different ways on Windows. For example, a developer needs to use Windows Forms to build a Windows GUI, or HTML/ASPX/Applets/JavaScript etc. to build a web interface, Windows Media Player or software such as Adobe's Flash Player for displaying video etc. The challenge for developers is certainly clear: building a coherent user interface for different kinds of clients using diverse technologies isn't a simple job.

A primary goal of WPF (originally called Avalon) is to address this challenge! By offering a consistent platform for these entire user interface aspects, WPF makes life simpler for developers. By taking a more modern approach, including support for video, animation, 2/3D graphics, and various kinds of documents, WPF can let users work with information in new ways. And by providing a common foundation for desktop clients and browser clients, WPF makes it easier to build applications that address both.

Another challenge that has long faced the creators of user interfaces stems from the different roles required for building effective interfaces. Software developers are needed to create the logic behind the interface, and Designers are required to define the interface's look and feel. Yet older technologies such as Windows Forms are focused entirely on the developer. There's no truly effective way for developers and designers to collaborate. To address this issue, WPF relies on the eXtensible Application Markup Language (XAML). An XML-based language, XAML allows specifying a user interface declaratively rather than in code. This makes it much easier for user interface design tools like MS Expression Blend (originally branded as MS Expression Interactive Designer and code named as Sparkle) to generate and work with an interface specification based on the visual representation created by a designer. Designers will be able to use such tools to create the look of an interface and then have a XAML definition of that interface generated for them. The developer imports this definition into Visual Studio, then creates the logic the interface requires.

Developers can also build a XAML browser application (XBAP) to create a remote client that runs inside a Web browser. Built on the same foundation as a stand-alone WPF application, an XBAP allows presenting the same style of user interface within a downloadable browser application. The best part is that the same code can potentially be used for both kinds of applications, which means that developers no longer need different skill sets for desktop and browser clients. The downloaded XBAP from the Internet runs in a secure sandbox (like Java applets), and thus it limits what the downloaded application can do.

Burp, GUI is a complex but an important part of the modern applications. Through WPF, the .NET Framework 3.0 presents a more complete and consistent solution to the challenges these interfaces present. The goal is to let people who create user interfaces (both developers and designers) effectively collaborate and do their jobs more expeditiously.

From the above information You could come to the conclution for below question's.
  • What is WPF and XAML?
  • What is the future of WPF and XAML over other technologies?.
  • How may I benefitted from using these two?. How it differs from others?.
  • Will it be a consistent one( For this you might get more idea from video module which is available in my last post(What Is WPF And It's Futures?).

I Hope everyone might came to the conclusion about those questions. if you want more about this topic please feel free to ask and i will post ASAP as per your requirement.

Please leave a comment and I'll cover them in my next post.

Thursday, April 26, 2007

What Is WPF And It's Futures?

Hi , here I am not going to explain about this topic.Directly WPF program manager going to explain about this topic. For understanding this just you need to spend 50 minutes in online because This is the video clip that shows demo about following futures. You could select topic directly from given combo box while playing demo application.

Demo application that shows off
  • Controls (rich functionality, rich content model, rich styling)
  • Interop with WinForms Controls
  • Layout (Panels)
  • Data Binding (DataTemplates)
  • Vector graphics
  • Text (this demo is commented out due to font licensing issues)
  • Reading (FlowDocument)
  • Save a FlowDocument to XPS
  • Media (Video)
  • 3d
  • Animation throughout

Here is the link and get idea and have a fun with WPF.

Still If you have a doubt please let me know i will try to give....

Enjoy!!!! !!!!!!!!!!!!!! Have a nice day ...

Wednesday, April 25, 2007

DataBinding In WPF

Today I will discuss about DataBinding that I have faced in my experience. please leave a comment and I'll cover them in my next post.

DataBinding is the technique of connecting controls and elements to the data. In the past, a programmer would write code both to initialize control from the variable and to set the variable into controls . In modern programing environments , the programmer defines a binding the control and variable , the binding automatically performs both the jobs.

Very often a data binding can replace an event handler, and simplifying the code. DataBinding are considered to have Source and Target. Here source is Data and Target is the Control and may be two controls will participate.

The bound property of the source need not be a Dependency property , but target property must be derived from the dependency object.

How can we bind data using {Binding} concept?
we can bind data between two elements or from resource collection. The following format is for bind with resource collections.

<!-- Resource Area-->
<system:String x:Key="myvar">Hi , This is Binding </system:String>

<!-- Bind With resource -->
//Method 1 (this method will bind whole object)
<TextBlock TextContent="{StaticResource myvar}" />

//Method 2 (this will bind particular property of object). it will display lenth property value of string .
<TextBlock Content="{Binding Source={StaticResource myvar}, Path=Length}" />

For Bind With Another Elements

<TextBlock Content="{StaticBinding Path=Length, ElementName=MyBox}" />
<TextBox Name="MyBox" />

Here textblock getting changes its content while typing the content on textbox.

Binding Modes

You can specify the mode property is separated from the path using comma.

Type of Mode

  1. OneWay -From the picture label get the value from source textbox. But it wont affect textbox value while the change happens in the label.

  2. TwoWay - From the picture Label get the from the Source textbox and also textbox will get the reflection while the change happens in the label.

  3. OneTime - From the picture Label initialized from the source textbox but does not track changes .

  4. OneWayToSource -if target property is not packed by a dependency property while source is . In that case we can use this mode.


DataContext is inherited through the element tree , so if you set it for one element it is also applies to all the children of that element. For example if we set the binding in stackpanel. We can bound properties of all the control under stackpanel.

Thursday, April 19, 2007

Freezable Object

A Freezable is a special type of object that has two states: unfrozen and frozen. When unfrozen, a Freezable appears to behave like any other object. When frozen, a Freezable can no longer be modified.

Freezable having Changed event to notify any changes in the object . Freezable can improve performance because it wont take more time to spend resources on changes. A Frozen Freezable can also be shared across threads. But unfrozen cant.Although the Freezable class has many applications, most Freezable objects in Windows Presentation Foundation (WPF) are related to the graphics sub-system.

Examples of types that inherit from Freezable include the Brush, Transform, and Geometry classes. Because they contain unmanaged resources, the system must monitor these objects for modifications, and then update their corresponding unmanaged resources when there is a change to the original object. Even if you don't actually modify a graphics system object, the system must still spend some of its resources monitoring the object, in case you do change it.

For example, suppose you create a SolidColorBrush brush and use it to paint the background of a button.

Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
myButton.Background = myBrush;

while painting the button on the screen , the SolidColorBrush doesn't actually do the painting , the Graphics System generates fast. low-level objects for the button and the brush, and it is those objects that actually appear on the screen. If you were to modify the brush, those low-level objects would have to be regenerated. The freezable class is what gives a brush the ability to find its corresponding generated, low-level objects and to update them when it changes. When this ability is enabled, the brush is said to be "unfrozen."

A freezable's Freeze method enables you to disable this self-updating ability. You can use this method to make the brush become "frozen," or unmodifiable.Here we are checking the object can freeze or not. Then if can means we can freeze using Freeze() method.

SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
if (myBrush.CanFreeze)
// Makes the brush unmodifiable.

Not every Freezable object can be frozen. To avoid throwing an InvalidOperationException, check the value of the Freezable object's CanFreeze property to determine whether it can be frozen before attempting to freeze it.

Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
myButton.Background = myBrush;
// Changes the button's background to red.
myBrush.Color = Colors.Red;

This sample first set the yellow color to Button , then will get change into the Red. after when get next page refresh. But it happening immediately after rendering the button.

Freezing a Freezable

To make a Freezable unmodifiable, you call its Freeze method. When you freeze an object that contains freezable objects, those objects are frozen as well. For example, if you freeze a PathGeometry, the figures and segments it contains would be frozen too. A Freezable can't be frozen if any of the following are true.

It has animated or data bound properties. It has properties set by a dynamic resource. (See the Resources Overview for more information about dynamic resources.) It contains Freezable sub-objects that can't be frozen.

Freezing from Markup

To freeze a Freezable object declared in markup, you use the PresentationOptions:Freeze attribute. In the following example, a SolidColorBrush is declared as a page resource and frozen. It is then used to set the background of a button.


<Page xmlns= xmlns:x= xmlns:PresentationOptions= xmlns:mc= mc:Ignorable="PresentationOptions">
<!-- This resource is frozen. -->
<SolidColorBrush x:Key="MyBrush" PresentationOptions:Freeze="True" Color="Red" />
<Button Content="A Button" Background="{StaticResource MyBrush}">

To use the Freeze attribute, you must map to the presentation options namespace: PresentationOptions is the recommended prefix for mapping this namespace:


Because not all XAML readers recognize this attribute, it's recommended that you use the mc:Ignorable Attribute to mark the Presentation:Freeze attribute as ignorable:


"Unfreezing" a Freezable

Once frozen, a Freezable can never be modified or unfrozen; however, you can create an unfrozen clone using the Clone or CloneCurrentValue method.

Creating Your Own Freezable Class

A class that derives from Freezable gains the following features.
  • Special states: a read-only (frozen) and a writable state.
  • Thread safety: a frozen Freezable can be shared across threads.
  • Detailed change notification: Unlike other DependencyObjects, Freezable objects provide change notifications when sub-property values change.
  • Easy cloning: the Freezable class has already implemented several methods that produce deep clones.

A Freezable is a type of DependencyObject, and therefore uses the dependency property system. Your class properties don't have to be dependency properties, but using dependency properties will reduce the amount of code you have to write, because the Freezable class was designed with dependency properties in mind. For more information about the dependency property system, see the Dependency Properties Overview which is posted by me.

Every Freezable subclass must override the CreateInstanceCore method. If your class uses dependency properties for all its data, you're finished.
If your class contains non-dependency property data members, you must also override the following methods:

  1. CloneCore
  2. CloneCurrentValueCore
  3. GetAsFrozenCoree
  4. GetCurrentValueAsFrozenCore
  5. FreezeCore


Wednesday, April 18, 2007

Attached Properties

Attached properties are a special form of dependency property. a child element can store a value associated with a property defined on an ancestor element. This is commonly used in the interaction between elements and the WPF layout infrastructure, such as an element informing a DockPanel that it should be docked to a particular side of the panel.

Reason for Attached properties:

When dealing with out Layout system, we want to provide the ability for anybody to build new Panels. Inside of those panels you should be able to put normal elements:

<Button />
<Button />

Often, the new panel will need to define a property that the user can place on the children of that panel to control how the panel arranges the children.

<Button RotationsPerMinute="60" />
<Button RotationsPerMinute="3"/>

Unfortunately that won't work. RotationsPerMinute is a newly invented property. The Button class shipped before the RobPanel was ever built and the Button class designers forgot to include this important property!

So WPF has the concept of attached properties. One class defines the property. You attach it to instances of other objects.

<Button Name="b1" my:RobPanel.RotationsPerMinute="60" />
<Button Name="b2" my:RobPanel.RotationsPerMinute="3" />

In C#.
RobPanel.SetRotatationsPerMinute(b1, 30);
int currentRotationsPerMinute = RobPanel.GetRotationsPerMinute(b1);

So if you buy the need for this extensibility, then you need to ask why is Canvas.Top and Canvas.Left modeled as an attached property, but Height and Width are modeled as normal properties.

Top and Left are modeled as attached properties because they are only respected inside of a Canvas. If I set Top or Left on a Button inside a StackPanel or DockPanel, it would have no effect.

Lets we will see an example for attached properties !

In this example i am creating new control named as MyControl with derived from Button. In which i am creating one attached property named as MyAttack.The attached property registration is like dependency property registration and for setting value we need to implement method with signature of SetPropertyName. This method should set the value for attached property using Dependencyobject.SetValue(value) method.

Code For UserControl

public class MyControl : Button
public static readonly DependencyProperty MyAttackProperty = DependencyProperty.RegisterAttached("MyAttack", typeof(bool), typeof(MyControl),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnMyAttackInvalidated)));
public MyControl()
public static void SetMyAttack(DependencyObject dependencyObject, bool enabled)
dependencyObject.SetValue(MyAttackProperty, enabled);
private static void OnMyAttackInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
Button b = dependencyObject as Button;
if (b != null)
if ((bool)e.NewValue)
MyControl m = new MyControl();
public void CallClick()

For Accessing Attached Property :

We can simply call the created attached property using classname.propertyname from any control attributes area. Like follow's.

<Window x:Class="AttachedProp.Window1" xmlns=
xmlns:x= xmlns:mn="clr-namespace:AttachedProp" Title="AttachedProp" Height="300" Width="300" >
<Button mn:MyControl.MyAttack="true" >Click</Button>

Output of this example should display messagebox with "Clicked" message after loading the button in window.


Dependency Properties

I have faced some interesting concept in WPF ,That one is Dependency Properties ,Its really sound cool.But it takes full day for me to get the complete idea. First I have tried to get the idea from some books.but I couldn't , Then I have visited some sites about DP. There i got some partial idea. Then again Book with couple of samples, Finally I got..

Its really interesting concepts in WPF.

The concept of dependency properties(what i have understood):

WPF contain window Element Tree. It consists of all the visual objects created by the program .For example iam creating 3 buttons and put them into the Grid ,then Grid into the Window. Here Window is the parent node ,grid is child node of window and buttons are child of Grid.

Visual Tree (Not a Logical Tree because Logical Tree contain all the elements like GridRowDefenitions , GridColDefenitions and Run object associated with text Block,etc..). Obviously this is not a complete visual tree because in visual tree may include visual objects that the program does not explicitly create. (E
x. Border,Background,etc..)

Here we have to take FontSize as a Dependency Property.

In WPF, if I try to change the FontSize of the window , It will change all the child elements fontsize automatically until the child element fontsize changed by explicitly, If we changed the fontsize of child element by explicitly it won't affect the original fontsize of that particular child element. But rest of the elements will get affect. This is called Dependency Properties.The interesting aspects is, In this visual tree Grid don't have a font size property even though the buttons font size will get changes,

Using this concepts we can create our own dependency properties for our custom controls. But our control class must be inherited by FrameWorkElement or UIElement class. Here fontsize isn't the only property that works like this. Allow-Drop ,IsEnabled,IsVisible,etc.. These are all UIElement class properties.

If you got! enjoy and leave your comments here!!!!!!!!!!!!!!!!!!!

Saturday, March 31, 2007

How To Create A Full Trust XBAP Application In WPF.

I recently faced some problem while creating XBAP application in WPF like trying to develop application which is contain IO file accessing from the browser application. As you may know, WPF Web Browser applications run in a sandbox, which allows them to be installed without any security prompts. However, there are cases, such as intranet applications, where allows an in-browser application to do more makes sense. which I thought I'd share to this with you people.

The Following Steps helps to produce Full trust XBAP Application.

Step 1:

Change the TargetZone of the appliction to custom. This can be done manually by hacking the .proj file or can be done in Visual Studio by going to Project Properties, going to the Security tab, and changing the dropdown to (custom).

Step 2:

Add the Unrestricted="true" attribute to the manifest of the appliction, which is located in the Properties folder. The manifest should look something like this.

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<defaultAssemblyRequest permissionSetReference="Custom" />
<PermissionSet class="System.Security.PermissionSet" version="1" ID="Custom" SameSite="site" Unrestricted="true"/>

Step 3:

Deploy the application using the Visual Studio Publish Wizard.

Step 4:

If you want to deploy this from the web, the certificate used to sign the manifest will have to be added to the Trusted Publishers store within Internet Explorer. By default, VS generates a .pfx key when you create a Web Browser application. Of course, real deployments, a company issued certificate would be more appropriate to use. Getting a cert into the store can be done by double clicking the cert or by using the certmgr tool with the appropriate commandline switches.

For some more Idea You may try with this ...

Enjoy !!!!! If You couldn't get ,please leave the comment about what you want exactly and what type of exception you are getting. It will try to give solution for your problem ..

Friday, March 30, 2007

Routed Events

Routed Events(This is another intresting concept in WPF)

Raising and handling events with the WPF is based on the new XAML markup structures, and how events are routed through a tree of elements. When a XAML page contains nested controls, there are interactive complexities that never before existed in the typical .NET UI environment.‘Nested’ controls create what is known as a Logical Tree and a Visual Tree.

Application developers have been required in times past to‘Walk-the-Tree’ by raising events and/or calling methods for each logical ‘node’ within a nested hierarchy.Events in the WPF are called Routed because there is a brand new chronological process by which to handle these events. This ordered, or routed, list of events will fire in a controlled fashion, providing full view of event the most complex Visual Trees. With the advent of Routed Events in the WPF.

The complications involved with capturing a series of hierarchical events are encapsulated and simplified. Routed Events are a pipeline of event handlers that are automatically fired for a control when any of its nested controls’ events fire. This means that it performs as a self-aware component, knowing when its members are being interacted with, and providing handler logic to respond to user or system related interactions.

A FrameworkElement could possible contain other sibling and child elements, which forms a tree of elements. In the WPF, the parent element can provide information to child elements, providing usage, customization, and visibility to the potentially smaller, nested objects. "Control Composition" is a term used to describe the creation or design concepts used when creating controls and providing thought to the handling of information within the tree. It leads developers to creating better structure for controls to control and direct the logical flow of events for the tree and its members.

Types of RoutedEvents
  1. Tunneling
  2. Bubbling
  3. Direct
A Bubbling event is the first place we will start, as it provides event handling from the originating element of a Visual Tree to the root of the tree. Tunneling event, on the other hand, fire in the opposite direction and are used to hook into the pre-condition of the controls within the visual tree from the top of the visual tree down. Tunneling and Bubbling event models assist in the complicated logic associated to events raised from / by controls within other controls. Developers can hook into an action before or after it occurs in context to its parent and child controls. Direct Event is typical .Net event handler concept.

Lets we will talk about RoutedEvent in detailed manner.

In WPF application contain many elements. You can see these elements in elements tree.(Such as visual tree). The routed event model enables you to use the element tree . This routed event will route along a route after its raised .It can travel in one of two directions. Event Listeners invoke the handlers from the root element to all successive child elements along the source element , this is called tunneling . And Event Listeners invoke the handlers from the source element to all successive parent elements along the Root element , this is called Bubbling Event.

Syntax For Routed Event

public static readonly RoutedEvent eventNameEvent;

Here event name followed by the word Event(Ex: TaskEvent)

The RoutedEvent instance obtained from registration is retained as a public static readonly field member of the class EventManager.ResgisterRoutedEvent.

Initializing Routed Event.


Note : Don't contain Event word with eventName(It should be like : Task)



Add and Remove Implementations(Initializing the Actual Event (language-specific))
we should define the actual event (ex : Task) , here the value argument is the event handler.

public event RoutedEventHandler Task
AddHandler(TaskEvent, value);

RemoveHandler(TaskEvent, value);

Use Of RoutedEvent

Group of controls together that should all interact. The parent element is a common listener for the routed event, and uses the same event handler whenever any of the controls raises a particular event.

Example :

In this example no need to write event handler for all the buttons , by using RoutedEvent can place a common Event Handler on the Parent of two buttons. (Here in windows).

Attaching and Implementing an Event Handler for a Routed Event

Attaching a handler for a routed event in an application that is created in code is also straightforward. Routed events almost always have background implementations of add and remove logic that allow the handlers to be added by a language-specific event syntaxRouted event handlers can also be attached through a helper method AddHandler.

Example of the helper method

Button b2 = new Button();
b2.Click += new RoutedEventHandler(myEvent);

void myEvent(object sender, RoutedEventArgs e)

Sample For Creating Custom RoutedEvent


class MyButton :Button
public static readonly RoutedEvent TaskEvent = EventManager.RegisterRoutedEvent("Task", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButton));
// Provide CLR accessors for the event
public event RoutedEventHandler Task
add { AddHandler(TaskEvent, value); }
remove { RemoveHandler(TaskEvent, value); }
// This method raises the Task event
void RaiseTaskEvent()
RoutedEventArgs newEventArgs = new RoutedEventArgs(MyButton.TaskEvent);
//Raise the event when the MyButton is clicked
protected override void OnClick()


public partial class Window1 : System.Windows.Window
public Window1()
// Creating Our Own Control for custom Routed Event
MyButton m=new MyButton();
m.Content ="Click Me";
m.Width =200;
m.Height =30;
this.Content = m;
m.Task += new RoutedEventHandler(m_Task);
void m_Task(object sender, RoutedEventArgs e)
MessageBox.Show("Hai Iam The Routed Event For Your Button");
// dont want to route others
e.Handled = true;
//throw new Exception("The method or operation is not implemented.");

Note : Here Task event will raise when you click on the mybutton. and it will show message box with message.

Key Points

For events that should be routed events

  • Declare a public static readonly field to hold your RoutedEvent object
  • Declare CLR accessors for these routed events
  • Declare a protected virtual void On( EventArgs e) method for subclasses to use. Call this method from your “class handler” -- EventManager.RegisterClassHandler(typeof(YourComponent), YourClassHandler).
  • Routed events using RoutingStrategy.Tunnel should have names that begin with “Preview”.
  • Many bubbling events don’t have corresponding tunnelling events, but almost all tunnelling events should have corresponding bubbling events.
  • A tunnelling event should be raised before its corresponding bubbling event. If the tunnelling event was marked as handled, the bubbling event should be marked as handled before the event is raised.

Still If You Cant Get, Try with this ....


Thursday, March 22, 2007

Layouts In WPF

Windows Presentation Foundation has dynamic layout (also known as automatic layout)
panel themselves are responsible for sizing ans positioning elements based on different layout models.

Type of Layout :(every layout derived from Panel Class)

  1. DockPanel
  2. Grid
  3. StackPanel
  4. UniformGrid
  5. WrapPanel

Panel defines a property names Children used to store the child elements. Children object can be UICollection. Like image,shape,textblock and control objects.


Its used to arrange the controls vertically or horizontal stack.


<Button> </Button>
<TextBlock> < /TextBlock>


StackPanel s=new StackPanel();
Button b=new Button();
TextBlock t=new TextBlock();

Orientation Property

We can specify the children orientation using Orientation property of StackPanel. s.Orientation=Orientation.Horizontal;

Vertical and Horizontal Alignment

s.HorizontalAlignment=HorizontalAlignment.Horizontal (or) s.VerticalAlignment=VerticalAlignment.Vertical


WrapPanel is similar to the StackPanel but in the WrapPanel Child elements can wrap to the next column or row automatically if there is not enough room. WrapPanel is used to add unknown number of controls like Non-Detail view in WindowsExplorer. And also we can set ItemHeight and ItemWidth properties that we can use to enforce uniform height or width, Orientation Property is same as StackPanel.

WrapPanel s=new WrapPanel();
Button b=new Button();
TextBlock t=new TextBlock();


use of the dockpanel is automates the positioning of elements against the inside edges of their parents. We can create dockpanel in C# Like Follows.

DockPanel d=new DockPanel();

And we can set dockpanel object into the window content property.

now window layout begin with dockpanel and then we can add other type panel or control like that . Adding children in dock panel is same syntax as with other panels.


But with that we need to specify on which side of the DockPanel you want control docked.
Example if you want dock the control on right side of panel you need to specify like this .

SetDock is a static method of DockPanel Class. Argument should be control and dock style.

Dock Enumeration


Note :
SetDock Method call may come before or after adding the control into the panel.

Another Method for setting Dock for the control

Using attached property concept like follows.

The last control is not docked at all but occupies the leftover interior space. This behavior is by default true setting of the DockPanel property LastChildFill. If we set LastChildFill=false means the last control also docked. And leftover space is unfilled .


its used to hosts the children in a grid of rows and columns. It has property named ShowGridLines. Its used to display the grid lines. GridLenth() is used to specify the Grid Height and Width. Constructor will take two arguments – one is value and another one is GridUnitType.


GridLenth glen=new GridLength(100,GridUnitType.Pixel);
Type Of GriUnit :


Grid g=new Grid();
RowDefinition rdef=new RowDefinition();
RowDefinition rdef1=new RowDefinition();
ColumnDefinition cdef=new ColumnDefinition();
ColumnDefinition cdef1=new ColumnDefinition();
Adding Control into the Grid.
Adding RowSpan and ColumnSpan


its similar to the Grid . Except that all the rows and columns are equal Height and Width.