Thursday, December 20, 2007

DataBinding in UserControl

Here are some guidelines to expose properties of inner Controls(Controls which are inside UserControl) through WPF UserControl.

Note: UserControl is not same as Control in which we are using Templates..
UserControl just holds other controls and wrap them.
  1. Create DP in UserControl.xaml.cs file same as of its child control.
  2. Bind this new DP with the inner control's DP
  3. Now you could use DP of inner control out side of UserControl

Here attached a sample which demonstrates this.

MyUserControl holds a slider and we are going to expose the Value DP of this through MyUserControl.

So add Value DP to MyUserControl and Bind that to Value DP of inner slider.

public partial class MySlider : System.Windows.Controls.UserControl
public MySlider()
public static readonly DependencyProperty ValueProperty=DependencyProperty.Register("Value",typeof(double),typeof(MySlider));
public double Value
return (double)GetValue(MySlider.ValueProperty);
SetValue(MySlider.ValueProperty, value);


Width="Auto" Height="Auto" x:Name="UserControl" >

<Slider Name="sldr" Value="{Binding Path=Value, ElementName=UserControl, Mode=TwoWay}" Width="100" />


Tuesday, December 11, 2007

Using Angle selector control of Blend in your application

If you have ever worked in Blend ,you would be familiar with the Angle selection control in blend.Sometimes this is refered as AngleSlider or in some other name.
But I think MSFT calls this as "RotationSpinner".(I got this name from a blend specific dll)

See this if you are still not able to identify the control.

This is a nice control which takes less space than slider and gives a great Visual appeal.Atleast once in a project time,you might thought of adding this control into your project :-)

Here an easy method to add this control into your project.I dont know whether MSFT allows this or not :-) .If Anybody have idea pls respond in comments.

  1. In your project add reference to "Microsoft.Expression.DesignSurface.dll".(Locate at C:\Program Files\Microsoft Expression\Blend 2 September Preview if you are using Sep preview)

  2. Select Asset library from toolbox and click on "CustomControls"

  3. Select "RotationSpinner" control and create its instance.

  4. Now you got the required control.Set its properties and go on..

Friday, November 2, 2007

Working with cookies in XBAP

2 methods to access cookies ie get and set


Application.GetCookie will raise exception if the cookie is not present..

Thursday, November 1, 2007

Remove control box of Paged WPF applications

  • Get the instance of the current Window from Application.Current and remove it's Control box by setting WindowStyle=None.

    public partial class Page1 : System.Windows.Controls.Page
    public Page1()

    this.Loaded += new RoutedEventHandler(Page1_Loaded);

    void Page1_Loaded(object sender, RoutedEventArgs e)
    Application.Current.MainWindow.WindowStyle = WindowStyle.None;


    Application.Current.MainWindow will be initialized only in Loaded event of Page

  • <Application.Resources>
    <Style TargetType ="{x:Type NavigationWindow}">
    <Setter Property ="WindowStyle" Value="None"/>

Wednesday, October 17, 2007

An extented VisualTreeHelper class

Usually if we want to get immediate parent of a Visual(Which considers the elements in Template also) we could use the VisualTreeHelper.GetParent method.This works easy for parent.
But think of getting the children of Visual..Its difficult to call VisualTreeHelper.GetChildren because this needs the index of child.
Here comes the role of this class which wraps these methods and makes its usage simple.


public static class VisualTreeHelperEx
public static T FindVisualAncestorByType<T>(DependencyObject dependencyObject) where T : DependencyObject
if (dependencyObject == null) return default(T);
if (dependencyObject is T) return (T)dependencyObject;
T parent = default(T);
parent = FindVisualAncestorByType<T>(VisualTreeHelper.GetParent(dependencyObject));
return parent;
public static T FindVisualChildByType<T>(DependencyObject dependencyObject) where T : DependencyObject
if (dependencyObject == null) return default(T);
if (dependencyObject is T) return (T)dependencyObject;
T child = default(T);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
child = FindVisualChildByType<T>(VisualTreeHelper.GetChild(dependencyObject, i));
if (child != null) return child;
return null;


Window W = VisualTreeHelperEx.FindVisualAncestorByType <Window>(grd);
Rectangle r= VisualTreeHelperEx.FindVisualChildByType<Rectangle>(grd)

Tuesday, September 25, 2007

Implementing Microsoft Office 2007 style zooming in WPF

This is a small code snippet which describes about implementing zooming action which is there in most of the components (MS Word 2007 etc) of Office 2007 package.

Basic idea is to put our content in a container and apply scale transform through LayoutTransform based on a slider value.

<Window x:Class="UntitledProject3.Window2"
Title="UntitledProject3" Height="300" Width="300"
<ScrollViewer Height="100" x:Name="scrl" HorizontalScrollBarVisibility="Auto" Background="{x:Null}" >
<TextBlock Height="19" Margin="0,0,0,0" x:Name="label1" Text ="This is our content">
<ScaleTransform ScaleX="{Binding Path=Value, ElementName=Slider, Mode=Default}"
ScaleY="{Binding Path=Value, ElementName=Slider, Mode=Default}"/>
<Slider Value="1" Minimum="1" Maximum="10" x:Name="Slider" />

Monday, September 24, 2007

More WPF custom control design time experience in Expression blend

Custom category editors
This is a continuation to my older post which described about custom property editors in blend.This post mainly discuss about creating a custom category editor and putting properties into that.
Here I am using more design specific mechanism with separate design time dlls, which was introduced with WPF technology.It helps us to keep our design time code in a separate dll which is suffixed with <assemblyname>.design.dll.You can get more information about the linking process between Control dll and design dll from here .

We are going to create a category named MyCategory like this


  1. Create metadata file in the design assembly ie in <customasembly>.design.dll
  2. Put the desired property into appropriate category using the category attribute.This is same as of Windows forms
  3. Create category editor and set its datatemplate.
  4. Use the editor attribute to associate this category editor into the custom control
  5. Open the solution in Blend.You can see your category editor

The new category with full customization

Some points to consider

  • Make sure that the design dll and application(which is using our custom control) is refering the same custom control assembly dll.Otherwise this wont get opened in blend.

For more details refer the sample here

Monday, September 17, 2007

Writing code behind for generic.xaml

Have you ever thought of a method which allows you to write code behind for your generic.xaml ?

If you fed up searching for such an option,here is the solution with 3 simple steps...

  1. Add a file named generic.xaml.cs
    • Right click on themes folder and select new class
    • Name it as generic.xaml.cs
  2. Change the definition of the class inside generic.xaml.cs as
    partial class generic :ResourceDictionary //This class should inherit from ResourceDictionary
  3. Link this code behind file to Gereric.xaml by using x:Class

    //The class name should be with namespace

Now you can write code for your generic.xaml elements in the generic.xaml.cs file.

The same method can be applied if you want to write code behind for any other xaml resource file.

A sample is attached here

Tuesday, August 7, 2007

3 dots (...) if space is insufficient

In older days if we want to put 3 dots (...), where there is no space to display full text,we have to do a bundle of calculations.

But in WPF its in built.Use


To get 3 dots...

<TextBlock Text="Joy George K" TextTrimming="CharacterEllipsis" />

Note : If you are using stack panel with orientation horizontal this wont work.If anybody have solution,please let me know.

Tuesday, July 24, 2007

Using ListView as DataGrid with the help of GridView

There is no native Data Grid in WPF.But we could achieve the behaviour with the help of ListView and GridView.

ListView has a property called View.Set a GridView to that property to get data displayed as DataGrid

Basic details
Sort columns upon header click

Control column width upon dragging

Wednesday, July 18, 2007

Host WPF controls in Windows forms & viceversa

Host WPF controls in windows forms

Host Windows forms controls in WPF

Better host winforms control into UserControl and then host that UserControl into WPF.So we wont lose designer facilities of windows forms control

Monday, July 2, 2007

Simple filtering in ListBox / CollectionView

The following code snippet will allow you to filter out unwanted items from your collection.

<Grid Name ="grd">
<XmlDataProvider x:Key="Company" XPath="/Company">
<Company xmlns="">
<Person Name="Jack" Role="CEO"/>
<Person Name="Tim" Role="PL" />
<Person Name="Jil" Role="PL" />
<Person Name="Jimmy" Role="PM" />
<Person Name="Joy" Role="PM" />
<Person Name="Jim" Role="PL" />
<Person Name="Jack" Role="PM" />
<DataTemplate x:Key="template">
<TextBlock Text="{Binding XPath=@Name}"/>
<CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource Company},XPath=Person}"
<ListBox Name="lst"
ItemTemplate="{StaticResource template}"
ItemsSource="{Binding Source={StaticResource cvs}}"/>

//Filter method
void src1_Filter(object sender, FilterEventArgs e)
System.Xml.XmlElement ele=e.Item as System.Xml.XmlElement;
string name=ele.Attributes[0].Value ;
if (name == "Tim") e.Accepted = true;
else e.Accepted = false;

This will display item "Tim".You may do custom filtering as you like in the filter method

Friday, June 29, 2007

Simple grouping in ListBox

<XmlDataProvider x:Key="Company" XPath="/Company">
<Company xmlns="">
<Person Name="Jack" Role="CEO"/>
<Person Name="Tim" Role="PL" />
<Person Name="Jil" Role="PL" />
<Person Name="Jimmy" Role="PM" />
<Person Name="Joy" Role="PM" />
<Person Name="Jim" Role="PL" />
<Person Name="Jack" Role="PM" />

<DataTemplate x:Key="categoryTemplate">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Background="ForestGreen" Margin="0,5,0,0"/>
<DataTemplate x:Key="template">
<TextBlock Text="{Binding XPath=@Name}"/>

<CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource Company},XPath=Person}">
<PropertyGroupDescription PropertyName="@Role"/>

<ListBox Name="lst"
ItemTemplate="{StaticResource template}"
ItemsSource="{Binding Source={StaticResource cvs}}">
<GroupStyle HeaderTemplate="{StaticResource categoryTemplate}" />

If you want to sort items in these groups please use SortDescriptions along with GroupDescriptions.For more details visit

Wednesday, June 27, 2007

Extending HeaderedItemsControl to have Footer !!!

The normal HeaderedContentControl in WPF gives us the facility to have a header up on the ItemsControl.This will be enough in most of the cases.But if you are looking for a ItemsControl which needs Footer too this is your solution.

  1. Solution 1

Use the Tag Property to hold Content of Footer.And Template it to have Footer.No inheritance!!!

<TextBlock Text="Item1" Background="LightGray"/>
<TextBlock Text="Item2" Background="LightGray"/>
<TextBlock Text="Item3" Background="LightGray"/>
<ControlTemplate TargetType="{x:Type HeaderedItemsControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<RowDefinition Height ="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<ContentPresenter ContentSource="Header" Grid.Row="0"/>
<ItemsPresenter Grid.Row="1" />
<ContentPresenter ContentSource="Tag" Grid.Row="2"/>

Hierarchical databinding into TreeView

<XmlDataProvider x:Key="Company" XPath="*">
<Reporting xmlns="">
<Person Name="CEO">
<Person Name="GM" >
<Person Name="PM-1" />
<Person Name="PM-2" >
<Person Name="PL" />
</Person >
<Person Name="PM-3" />
<Person Name="PM-4">
<Person Name="PL-2" />
<Person Name="PL-3" />
<Person Name="PM-5" />
<HierarchicalDataTemplate DataType="Person" ItemsSource ="{Binding XPath=*}">
<TextBlock Text="{Binding XPath=@Name}" />

<TreeView ItemsSource="{Binding Source={StaticResource Company}, XPath=*}"/>

Thursday, June 21, 2007

How to specify which property of my custom class should take the Content from xaml?

Use System.Windows.Markup.ContentProperty attribut on the class
If you are creating a custom class for clock control and wanna Time to take the Content from xaml use as follows.

public class Clock : Control {
public DateTime Time{

Hence the xaml looks like

<MyControl:Clock >
</MyControl:Clock >

Tuesday, May 22, 2007

Commenting XAML elements

Normally if you want to comment a particular element (Button.Content)in the tag like the below one,usually select the element and select the comment option from VS toolbar or menu.
This works with c# code .But wont with xaml.It produces a compilation error.

<Button Name="btn" Content="Hai" Click="clicked"/>

TO get rid of this use as follows

<Window x:Class="BlendControl.Window1"
<StackPanel >
<Button Name="btn" c:Content="Hai" Click="clicked"/>

This nicely comment the Content element.

Vista V/S Linux

Just see a comparison

Accociate schema to custom namespaces

If we analyze a xaml file we could see 2 lines at the beggining.


These lines map the namespaces to xaml file.Whenever we need to refer our own custom dll we often use the following format .


We could also use the URL type mapping for our own controls.For this we need to include the following 3 lines in the Assemblyinfo.cs file of our custom dll.

  • Add a reference to using System.Windows.Markup;
  • Add 2 attributes

[assembly: XmlnsPrefix("", "mycontrols")]
[assembly: XmlnsDefinition("", "MyControls")]

Now you could use like the following in your xaml file to refer custom dll


A sample here

Thursday, May 17, 2007

Creating Custom property editors for Blend & Orcas

Explaining how to create custom property editors for Blend & Orcas using WPF features.

  • A latest version of Blend.Preferably May 2007 CTP
  • Microsoft's new design dll .This is in .net3.5.You may also use this with 3.0.

I am taking famous Clock control from codeproject and implementing the custom property editor


  1. Get the sample from code project.
  2. Open the sample and make a reference to new design dll.If you already have orcas 1(3.5) it would be in your machine.Else download from here.
  3. Prepare the DataTemplate of the property editor.Better save in the generic.xaml file itself.An eg given below

    <DataTemplate x:Key="TimeEditorDataTemplate">
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="Auto"/>
    <TextBox Text="{Binding Path=Value, Mode=TwoWay}"/>
    <PropertyEditing:EditModeSwitchButton Grid.Column="1" Content="Change"/>

  4. Create our own editor by inheriting from Microsoft.Windows.Design.PropertyEditing.DialogPropertyValueEditor
  5. Set the DataTemplates..See the below code

    public class TimeEditor : Microsoft.Windows.Design.PropertyEditing.DialogPropertyValueEditor {

    public TimeEditor(): base() {
    //This is to get the DataTemplate of editor from generic.xaml file Uri

    resourceLocator = new Uri("MyControls" + @";component/themes/generic.xaml", UriKind.RelativeOrAbsolute);
    ResourceDictionary rd = (ResourceDictionary)Application.LoadComponent(resourceLocator);
    DataTemplate dt = rd["TimeEditorDataTemplate"] as DataTemplate;
    this.InlineEditorTemplate = dt;
    this.DialogEditorTemplate = dt; } }

  6. Now set the editor into desired property

    [Editor(typeof(TimeEditor), typeof(DialogPropertyValueEditor))]
    public DateTime MyTime {
    get{ return (DateTime) GetValue(MyTimeProperty); }
    set{ SetValue(MyTimeProperty, value); }

  7. Yes.Thats it.Instantiate your control in Blend and see the PROPERTYEDITOR

Download full sample here

Its a great design time experience with designers (Visusl studio ExpressionBlend). Right?

More details

Monday, May 14, 2007

Videos showing Power of WPF

INK Features


Yahoo messenger for Vista

Writing C# inside XAML

<Grid >

<Button Name="button1" Click="Clicked" Content="Click Me!"/>
void Clicked(object sender, RoutedEventArgs e)
button1.Content = "Hello World";


Friday, May 11, 2007

Prototype of Next gen 3D Desktop using WPF

A model of windows desktop which may arrive in the near future using the WPF technology

Thursday, May 10, 2007

Difference Vector graphics & Raster graphics

Raster graphics stores the image as pixel array and when resizing it resizes that image.Quality loss is the result like photoshop resizing.
Vector graphics stores the image as data (how to draw an image) and scales that data and draws when needed .So no quality loss.

Wednesday, May 9, 2007

How to know the current rendering mode of WPF application?

Check the value (System.Windows.Media.RenderCapability.Tier >>16 ) .Results are given as follows
  • 0-Software rendering
  • 1-Partial rendering
  • 2-Hardware rendering

According to this we could load different Resources(which contain styles & templates) in order to maintain same performance in different machines.

Some great WPF applications..

  1. Dropping balls and cubes from the top and they get their right place according to gravity/available space.
  2. Virtual earth
  3. Mother earth
  4. Chart
  5. Book control demo.

Tuesday, May 8, 2007

Target an inner element from setter

Consider a scenario where we need to change the second color of a gradient on mouse over.The normal solution will be as follows.

<ControlTemplate TargetType="Button">
<Rectangle Width='60' Height='40' x:Name='MyRectangle'>
<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='Blue' Offset='1' x:Name='SecondStop' />
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName='MyRectangle' Property="Fill" >
<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='Green' Offset='1' />

If we folllow this method we need to write the same code twice.If there is a method to change the value of second color directly,it would be more easier to code.The below code does it with the help of binding.

<ControlTemplate TargetType="Button">
<Rectangle Width='60' Height='40' x:Name='MyRectangle'>


<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='{Binding ElementName=MyRectangle, Path=Tag}' Offset='1' x:Name='SecondStop' />
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName='MyRectangle' Property="Tag" Value="Green" >

Thursday, May 3, 2007

Advantages of WPF & .net3

Some advantages of WPF ,I found while working with WPF
  1. Cool applications in less time.
  2. Effective use of Graphics card.Highly suitable for high end /upcoming computers.
  3. We can create 3D scenes very easily.(Using ViewPort3D)
  4. Databinding
  5. Built in Animation
  6. Templates & Styles
  7. Resource management
  8. Content control mechanism.
  9. XAML(Designer and developer can work independently)
  10. XBAP
  11. Silverlight (WPF/e)
  12. Same programming model for windows & web
  13. Retained mode graphics (No need to draw in the OnPaint event.Everything automatic)
  14. Supports most of the media/document formats natively


  1. WPF/e doesnt have support to add controls in it.Hope they implement it soon.
  2. We need to go for another software (Blend)if we want to design a good looking interface.VS should have all the facilities what Blend does now.
  3. No MDI child mode.

Friday, April 20, 2007

Refering inner element through XAML

<StackPanel >
<TextBlock Text="{Binding ElementName=btn,Path=Foreground.Color.R}">
<Button Foreground="Red" Name="btn"/>


Get the template of 3rd party controls

If we dont have template of a Control we could get that using Blend.
Load the control in Blend and right click on it then select

Edit Control Parts(Template) -> Edit a Copy

This will create a copy of the template in xaml file.

Vista theme support in XP using WPF

This wont change the look and feel of the Window as in Vista ie the transparent window title.But changes the look and feel of the elements (Button,Combo etc) inside that Window.

Know the state of a object in XAML format at runtime

The below code gives the XAML representation of object at runtime.


Using this we can save the current state of the objects..

Creating a control from xaml string at runtime

string s = "< Button xmlns='' xmlns:x='' >";
s += "Hai";
s += " < /Button > ";

Stream strm = new MemoryStream(ASCIIEncoding.Default.GetBytes(s));
Button b = (Button)System.Windows.Markup.XamlReader.Load(strm);

How can we make a TextBox looks like Button using template?

If we wanna make the Button looks like TextBox it is easy,just add the TextBox as content of Button.But the reverse is not possible sice TextBox doesnt have Content property.So use Templating.

< TextBox Text="Hai" >
< TextBox.Template >
< ControlTemplate >
< Button Content="hai"/ >
< /ControlTemplate >
< /TextBox.Template >
< /TextBox >

CS Code

ControlTemplate ct=new ControlTemplate(typeof(TextBox));
FrameworkElementFactory fef=new FrameworkElementFactory(typeof(Button));
ct.VisualTree =fef;
txt.Template = ct;

Thursday, April 19, 2007

Access yahoo through XAML in WPF

See this and know how to access the information on yahoo through XPath

Start WPF 3D here

This helps us to understand what is Mesh,Normals etc and finally make us capable of creating a cube

Some WPF tutorial sites

WPF tutorials

Cheat sheets
WPF XAML Data Binding Cheat Sheet (PDF), latest version, updated February 2
 XAML for WPF Cheat Sheet 1.0

Some XAML & XBAP tutorials



WPF 2D controls in 3D viewport

Get the library from below link which helps us to include 2d controls like Button,Textbox etc into 3D viewport.

Also this will raise all the events such as Click,MouseDown of 2D controls.

New confusing things in WPF

DependencyObject and DependencyProperty
Logical and VisualTree
Tunnel and Bubble events
XBAP and Standalone applications
ControlTemplate and DataTemplate
Style and Template
Need to complete

Command and Event
Window and Page

Static and Dynamic resources

Tricks and tips in WPF / How to achieve things using WPF

Applying same style to all wpf elements of same type

The folloging code will give a Red background to all the Buttons in the Window provided if we didnt set the ButtonBackground explicitly

< Window.Resources >
< Style x:key="{x:Type Button}" TargeType="{x:Type Button}" >
< Setter Property ="Background" Value ="Red"/ >
< /Style >
< /Window.Resources >

C# Code

Style sty = new Style(typeof(Button));

Setter set = new Setter(Button.BackgroundProperty , Brushes.Red);


Resources.Add(typeof( Button), sty);


Sharing My WPF experiences....
The posts will contain links more which are useful than my own articles :-)