MVVM – Using ContentTemplateSelector in Tab Control View


I have a WPF TabView Control and Two Tab Items each containing different Tab Item Contents . I need to express this using MVVM / Binding.

ContentTemplateSelector is the place to go.

In the demo, we would have one TabView with two Tabs, they are

    1. Countries Tab, and
    2. Continents Tab.

Download Sample Project here:


1. Create two Views (user Control) i.e. CountryView.xaml and ContinentsView.xaml, one for each tab item content.
2. Create a ViewModel for the Tab Control, here Tabs represent the TabItem’s

public class MyTabControlViewModel
        public List<MyTabItemModel> Tabs { get; set; }

3.  Create TabItemModel Class

public class MyTabItemModel
        /// <summary>
        /// Tab Header text
        /// </summary>
        public string Header { get; set; }

        /// <summary>
        /// Tab Content 
        /// </summary>
        public IMyTabContentViewModel CurrentMyTabContentViewModel { get; set; }

4 .Create the Content Interface and implement the Content Views

public interface IMyTabContentViewModel
    public class CountryTabContentViewModel : IMyTabContentViewModel
    public class ContinentTabContentViewModel : IMyTabContentViewModel

5. Define two Data Templates, one for “Country view ” and another for “Continents view

<DataTemplate x:Key="CountryContentTemplate">
  <View1:CountryView DataContext="{Binding CurrentMyTabContentViewModel}"/>

<DataTemplate x:Key="ContinentsContentTemplate">
            <View1:ContinentsView DataContext="{Binding CurrentMyTabContentViewModel}"/>

6. Create a Selector Class derived from DataTemplateSelector:

public class MyViewSelector : DataTemplateSelector
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
            if (((MyTabItemModel)(item)).CurrentMyTabContentViewModel is CountryTabContentViewModel)
                return CountryTemplate;
            return ContintentsTemplate;
        public DataTemplate CountryTemplate {get;set;}

        public DataTemplate ContintentsTemplate{get;set;}

7. Assign the DataTemplates to the appropriate Selector properties

<ViewModel:MyViewSelector x:Key="selector" 
    CountryTemplate="{StaticResource CountryContentTemplate}"
    ContintentsTemplate="{StaticResource ContinentsContentTemplate}" />

8. Map the ContentTemplateSelector property to the Selector. Your TabControl would look like this :

<UserControl x:Class=”TabControlItemTemplateDemo.View.MyTabControl”
             xmlns:View1=”clr-namespace:TabControlItemTemplateDemo.View” mc:Ignorable=”d”
             d:DesignHeight=”300″ d:DesignWidth=”300″>
        <DataTemplate x:Key=”MyTabHeaderTemplate”>
                    <ColumnDefinition Width=”*” />
                <TextBlock Grid.Column=”0″ Text=”{Binding Header}” Width=”80″ Height=”25″ FontWeight=”Bold”/>
        <DataTemplate x:Key=”CountryContentTemplate”>
            <View1:CountryView DataContext=”{Binding CurrentMyTabContentViewModel}”/>
        <DataTemplate x:Key=”ContinentsContentTemplate”>
            <View1:ContinentsView DataContext=”{Binding CurrentMyTabContentViewModel}”/>
        <ViewModel:MyViewSelector x:Key=”selector”
                                           CountryTemplate=”{StaticResource CountryContentTemplate}”
                                           ContintentsTemplate=”{StaticResource ContinentsContentTemplate}” />
        <TabControl ItemsSource=”{Binding Tabs}” TabStripPlacement=”Left”
                    BorderThickness=”0″ Background=”White”
                    ItemTemplate=”{StaticResource MyTabHeaderTemplate}”
                    ContentTemplateSelector=”{StaticResource selector}”>

Download Sample Project here:


MVVM – Binding TreeView Item Changed to ICommand

Download Sample Project here:

After browsing the web for more tha an hour there were quite some post which helped me to get a clue on how to bind a Tree View item selected.
All these posts gave me call back, on which I had to fire an event again, and add a subscription to it.

I wanted that call back subscription to be an ICommand, so that it is in sync with MVVM model.
But to bring the Call back into the View model had to go an extra mile.

I had to synchronize two dependency property.

1.  A dependency property to bind to  TreeView Item Selected .
2.  A dependency property to bind an ICommand, to  TreeView Item Selected Changed.

Dependency property to bind the TreeView Item Selected:

You need a dependency property which would hold the Tree View Item Selected value.
This property should be always updated with the New value, so that you would get an call back on SelectedItemChanged when a new item in the tree is selected.

public static readonly DependencyProperty SelectedItemProperty =
                                 new UIPropertyMetadata(null, SelectedItemChanged));

Dependency property to bind an ICommand, when an TreeView Item Selected is changed:

You need a second dependency property which you could bind to an ICommand and execute when ever a new item in the treeview is selected.

public static readonly DependencyProperty SelectedItemChangedProperty =

Code to fire the ICommand on SelectedItemProperty call back events

private static void SelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    if (!(obj is TreeView) || e.NewValue == null)

    var view = obj as TreeView;
    view.SelectedItemChanged += (sender, e2) => SetSelectedItem(view, e2.NewValue);

    var command = (ICommand) (view as DependencyObject).GetValue(SelectedItemChangedProperty);
    if (command != null)
        if (command.CanExecute(null))
            command.Execute(new DependencyPropertyEventArgs(e));

Here is the xaml code to bind these two dependency properties

<UserControl x:Class="TreeViewItemChangedMvvm.View.MyTreeViewControl"
             xmlns:ViewModelUtils="clr-namespace:TreeViewItemChangedMvvm.ViewModelUtils" mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
        <TreeView ItemsSource="{Binding ItemsSource}"  
                  ViewModelUtils:TreeViewHelper.SelectedItem="{Binding CurrSelItem}"  
                  ViewModelUtils:TreeViewHelper.SelectedItemChanged="{Binding MySelItemChgCmd}" />

Sample Project:

Setting up Android Development platform – Eclipse

Here is in brief the steps required to set up the Android development environment
1. Download – Eclipse Helios version – Choose 32bit or 64bit from the right side based on ur system configuration – I used 32 bit.
    Link:   Download Here
2. Download: JDK – Java SE Development Kit 6u24
     Link:   Download Here
3. First Install JDK (downloaded in Step2).
4. Unzip Eclipse (downloaded in step1) and Launch ‘eclipse.exe’
5. Follow the procedure here – where you get the Android Development Tools (ADT) which is a plugin for the Eclipse IDE.   Link:  Info Here
6.  Download Android SDK.
      Link: Download Here  ,  download the .exe version and run it. On finish it will launch the SOFTWARE MANAGER. Just select and continue/OK.
It will install all the updates. It contains the platforms in it.
I took me almost the whole day to get to this point.. Curse my broadband speed.. Hufff..
Now its high time we  get our hands wet.. Happy Coding 🙂

Extension Method to Reverse an integer in c#

Was interviewing a campus student for our team, with one of my colleague. We asked her to write a code snippet, to reverse an integer.

The only programming language that she knew was C.  She wrote a program in C, which had almost 20-25 lines of code. It wasn’t too neat, but was pretty good for a campus student.

After the interview, I was wondering,  how should a guy working with C# for around 5years answer it.

And thought this could be good way to write it.

There are much better ways, this one uses  Extension Methods,  Lamda Expressions, to solve a simple problem.

I feel the best way to learn a language, is to make simple things complex, just like above ;).