Click here to Skip to main content
14,873,128 members
Articles / Desktop Programming / WPF
Posted 5 Jul 2008


43 bookmarked

Selecting the Detail Level to View at Runtime in WPF

Rate me:
Please Sign up or sign in to vote.
4.78/5 (23 votes)
5 Jul 2008CPOL7 min read
Explains how to allow users to select the amount of information to view


This article examines a small WPF program that allows the user to choose the amount of detail to view about each data item in a list. The concept behind this feature is very similar to the “Views” feature in Windows Explorer on Vista, as seen below:



Very often, a user interface provides too little or too much information for a particular user’s needs. It is impossible for developers and designers to create the perfect UI for all users of an application, especially if it has many users. The next best option is to allow the user to decide what information he/she wants to view. Applications often provide this by allowing the user to select which fields to view in a data grid, or having an ‘Advanced’ screen in an Options dialog, etc. This article shows how to implement this feature by allowing the user to adjust a Slider control to decide how much information to view about each item in a list.

The Demo App

At the top of this page, you can download the sample program that accompanies the article. When you run that application, and decrease its height, it looks like this:


The UI essentially consists of an ItemsControl and a Slider control. The ItemsControl displays a collection of Person objects, and the Slider determines what level of detail displays about each person. If you were to move Slider a bit to the right, the UI would then look like this:


Now each person’s age appears in parentheses next to his/her name. Moving the Slider even further to the right would result in a UI like this:


At this point, we can see each person’s name, age, and gender. The Slider still has more room to move, so let’s see what happens if we slide it all the way to the right and resize the Window a bit.


The UI changes considerably when the program is displaying the highest level of detail. The same display text appears for each person, but we now see his or her photo and either a blue or pink background color, based on the person’s gender.

Pushing the WPF Envelope

A WPF programming problem like this has many solutions, each with its relative merits. It turns out that the approach I consider best is not something that WPF supports very well at all. I believe that I have found a border case scenario that WPF should support, but it instead introduces an artificial limitation that required a workaround. I have been working with WPF long enough to know the “WPF way” of doing things, and in this situation, I believe WPF does not have proper support for the WPF way of solving this problem. Perhaps I just need to get out more…

The Ideal Implementation

There is a Slider and an ItemsControl. The ItemsControl displays information about people, and the Slider’s value determines how much information displays for each person. Each available level of detail requires that a certain DataTemplate render the Person objects. We must apply the appropriate DataTemplate to the ItemTemplate property of the ItemsControl, based on the value of the Slider. There is a direct relationship between the ItemsControl’s ItemTemplate property and the Slider’s Value property. Therefore, those two properties should be bound to each other, via WPF data binding. As we will see later, WPF does not make it easy to implement this approach because there is no supported way for a value converter to perform a resource lookup.

Implementing this entire feature should require just one binding. Sure, we could easily throw some code into the Window’s code-behind file, handle the ValueChanged event of the Slider, figure out which template to use by looking at the Slider’s Value, and then assign the correct DataTemplate to the ItemsControl. To me, that is a terrible option. That is treating the Window’s code-behind as a dumping ground for code that does not belong there. By that line of reasoning, we should also put an application’s data access logic, business logic, and grandma’s kitchen sink in there as well! We certainly can, and will, do better than that.

How It Works

I created a simple Person class and, in the Window’s constructor, assigned an array of them to the ItemsControl’s ItemsSource property. That code is below:

public partial class Window1 : Window
    public Window1()

        _personList.ItemsSource = new Person[]
            new Person("Buster Wankstonian", 101, 'M', "buster.jpg"),
            new Person("Pam van Slammenfield", 18, 'F', "pam.jpg"),
            new Person("Peter Bonklemeister", 42, 'M', "peter.jpg"),
            new Person("Sarah Pilgrimissimo", 26, 'F', "sarah.jpg"),
            new Person("Teresa McPuppy", 72, 'F', "teresa.jpg"),
            new Person("Zorkon McMuffin", 30, 'M', "zorkon.jpg"),

We know that the application has a notion of “detail levels”, so it makes sense to create an enumeration that represents those various levels. The DisplayDetailLevel enumeration is below:

/// <span class="code-SummaryComment"><summary></span>
/// Represents various settings for how much information
/// should be displayed to the end-user.
/// <span class="code-SummaryComment"></summary></span>
public enum DisplayDetailLevel
    Low = 1,
    Medium = 2,
    High = 3,
    VeryHigh = 4

DataTemplates for Person Objects

At this point, if we were to run the program, the ItemsControl would display each Person object by simply displaying its fully qualified type name. In order to display each Person object in a meaningful way, we need to create a DataTemplate with which the ItemsControl can render each Person. However, since the rendering of a Person changes based on the level of detail to show, we need one template for each detail level. I created four DataTemplates and put them into the PersonDataTemplates.xaml file, which is a ResourceDictionary that is loaded into the resource hierarchy at runtime. That ResourceDictionary is below:

  <!--<span class="code-comment"> LOW --></span>
  <DataTemplate x:Key="{x:Static local:DisplayDetailLevel.Low}">
    <TextBlock Text="{Binding Path=Name}" />

  <!--<span class="code-comment"> MEDIUM --></span>
  <DataTemplate x:Key="{x:Static local:DisplayDetailLevel.Medium}">
        <TextBlock Text="{Binding Path=Name}" />
        <TextBlock Text="{Binding Path=Age}" Margin="-4,0" />

  <!--<span class="code-comment"> HIGH --></span>
  <DataTemplate x:Key="{x:Static local:DisplayDetailLevel.High}">
      <TextBlock Text="{Binding Path=Name}" />
      <TextBlock Text="{Binding Path=Age}" Margin="-4,0" />
      <Run>) -</Run>
      <TextBlock Text="{Binding Path=Gender}" />

  <!--<span class="code-comment"> VERY HIGH --></span>
  <DataTemplate x:Key="{x:Static local:DisplayDetailLevel.VeryHigh}">
      Width="300" Height="250"
        <!--<span class="code-comment"> Inject the 'High' template here for consistent display text. --></span>
          Content="{Binding Path=.}"
          ContentTemplate="{StaticResource {x:Static local:DisplayDetailLevel.High}}"
        <Image Width="250" Height="200" Source="{Binding Path=PhotoUri}" />
      <DataTrigger Binding="{Binding Path=Gender}" Value="F">
        <Setter TargetName="bd" Property="Background" Value="Pink" />
      <Trigger Property="IsMouseOver" Value="True">
        <Setter Property="BitmapEffect">
            <DropShadowBitmapEffect />

There are two important things to notice about the above XAML. Each DataTemplate’s x:Key is a value from the DisplayDetailLevel enumeration we saw earlier. That fact will come into play later, when we see how the DataTemplates are located and applied. The other point of interest is how the ‘VeryHigh’ template makes use of the ‘High’ template to ensure that each has identical display text. This trick is accomplished by putting a ContentControl into the DataTemplate, assigning its ContentTemplate to the ‘High’ template, and binding its Content property to the containing template's inherited DataContext (via the “{Binding Path=.}” notation). This technique prevents us from having to duplicate the ‘High’ template declaration in the ‘VeryHigh’ template, which is great for maintenance and readability.

UI Controls and Resources

Next, we will look at the XAML for the controls seen in the Window. For the time being, I have omitted the Resources of the DockPanel, just so that we can focus on the controls. Later we will see the resources, too.

      Text="Detail Level:" 
      Minimum="1" Maximum="4" 
      SmallChange="1" LargeChange="1" 
        Converter={StaticResource DetailLevelConv}}"

The most important thing to observe is how the ItemsControl has its ItemTemplate property bound to the Value property of the Slider. That binding accurately expresses the relationship between those two controls, but, naturally, it makes no sense to directly bind a property of type Double to a property of type DataTemplate. That is why the binding’s Converter property references a value converter, whose resource key is DetailLevelConv. Now we will check out the resources used in this UI.

    <!--<span class="code-comment"> 
    Merge in the dictionary of DataTemplates. 
      <ResourceDictionary Source="PersonDataTemplates.xaml" />

    <!--<span class="code-comment"> 
    This converter must be in an element's Resources collection
    for it to be a valid source of a resource lookup.
    <local:ResourceKeyToResourceConverter x:Key="ResourceConv" />

    <!--<span class="code-comment"> 
    This converter group transforms a Double into a DataTemplate.
    <local:ValueConverterGroup x:Key="DetailLevelConv">
      <local:DoubleToDisplayDetailLevelConverter />
      <StaticResourceExtension ResourceKey="ResourceConv" />

The merged dictionary is importing all four DataTemplates that render Person objects. We already saw those previously. After that, there are three value converters. ValueConverterGroup is a class I made and wrote an article about back in August 2006. It chains together any number of IValueConverter objects, treating the output of one converter as input of the next converter. I use that tool here to combine two new value converters together.

The task of transforming a Slider’s Value into a DataTemplate can be seen as two separate steps. First, we must translate a Double into a value from the DisplayDetailLevel enumeration. Then we must perform a resource lookup to find the correct DataTemplate, by using the DisplayDetailLevel value as the resource key. This is why I set each DataTemplate’s x:Key to a value of the DisplayDetailLevel enumeration; so that we can easily locate the template via the current detail level setting.

Converting a Double to a DisplayDetailLevel

Here is the value converter responsible for translating a Double to a DisplayDetailLevel value:

[ValueConversion(typeof(Double), typeof(DisplayDetailLevel))]
public class DoubleToDisplayDetailLevelConverter : IValueConverter
    public object Convert(
      object value, Type targetType, object parameter, CultureInfo culture)
        if (value is double == false)
            return Binding.DoNothing;

        int num = System.Convert.ToInt32(value);

        if (num < 1 || 4 < num)
            return Binding.DoNothing;

        return (DisplayDetailLevel)num;

    public object ConvertBack(
      object value, Type targetType, object parameter, CultureInfo culture)
        throw new NotSupportedException("Cannot convert back");

Performing a Resource Lookup from a ValueConverter

The converter that performs the resource lookup was much trickier to write. It relies on some dirty hack magic to get the job done. If you have a policy that forbids you from relying on reflection to manipulate implementation details of the .NET framework, then you cannot use this class in your applications. This class relies on the Hillberg Freezable Trick and some homegrown reflection madness to coerce WPF into allowing a value converter to perform a resource lookup. Here is my ResourceKeytoResourceConverter class:

/// <span class="code-SummaryComment"><summary></span>
/// A value converter that performs a resource lookup on the conversion value.
/// <span class="code-SummaryComment"></summary></span>
[ValueConversion(typeof(object), typeof(object))]
public class ResourceKeyToResourceConverter
    : Freezable, // Enable this converter to be the source of a resource lookup.
    static readonly DependencyProperty DummyProperty =

    public object Convert(
      object value, Type targetType, object parameter, CultureInfo culture)
        return this.FindResource(value);

    public object ConvertBack(
      object value, Type targetType, object parameter, CultureInfo culture)
        throw new NotSupportedException("Cannot convert back");

    object FindResource(object resourceKey)
        // NOTE: This code depends on internal implementation details of WPF and 
        // might break in a future release of the platform.  Use at your own risk!

        var resourceReferenceExpression =
            new DynamicResourceExtension(resourceKey).ProvideValue(null)
            as Expression;

        MethodInfo getValue = typeof(Expression).GetMethod(
            BindingFlags.Instance | BindingFlags.NonPublic);

        object result = getValue.Invoke(
            new object[] { this, DummyProperty });

        // Either we do not have an inheritance context or the  
        // requested resource does not exist, so return null.
        if (result == DependencyProperty.UnsetValue)
            return null;

        // The requested resource was found, so we will receive a 
        // DeferredResourceReference object as a result of calling 
        // GetValue.  The only way to resolve that to the actual 
        // resource, without using reflection, is to have a Setter's 
        // Value property unwrap it for us.
        var deferredResourceReference = result;
        Setter setter = new Setter(DummyProperty, deferredResourceReference);
        return setter.Value;

    protected override Freezable CreateInstanceCore()
        // We are required to override this abstract method.
        throw new NotImplementedException();

It is important to note that for ResourceKeyToResourceConverter to work properly, you must add it directly to the Resources of an element. You cannot add it to a separate ResourceDictionary that is assigned to an element’s Resources or merged into an existing ResourceDictionary. The reason for this is that it relies on undocumented internal behavior of WPF to ensure the converter receives an inheritance context, which only happens properly when the converter is added directly to an element’s Resources. This also explains why I had to add that converter to the ValueConverterGroup via a StaticResourceExtension, instead of adding it inline. Here is that XAML again:

<!--<span class="code-comment"> 
This converter must be in an element's Resources collection
for it to be a valid source of a resource lookup.
<local:ResourceKeyToResourceConverter x:Key="ResourceConv" />

<!--<span class="code-comment"> 
This converter group transforms a Double into a DataTemplate.
<local:ValueConverterGroup x:Key="DetailLevelConv">
  <local:DoubleToDisplayDetailLevelConverter />
  <StaticResourceExtension ResourceKey="ResourceConv" />

Cast and Crew


Revision History

  • July 5, 2008 – Published my fiftieth article on The Code Project!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Josh Smith
Software Developer (Senior) Black Pixel
United States United States
Josh creates software, for iOS and Windows.

He works at Black Pixel as a Senior Developer.

Read his iOS Programming for .NET Developers[^] book to learn how to write iPhone and iPad apps by leveraging your existing .NET skills.

Use his Master WPF[^] app on your iPhone to sharpen your WPF skills on the go.

Check out his Advanced MVVM[^] book.

Visit his WPF blog[^] or stop by his iOS blog[^].

See his website Josh Smith Digital[^].

Comments and Discussions

GeneralThanks Pin
Dr.Luiji17-Jul-08 10:46
professionalDr.Luiji17-Jul-08 10:46 
GeneralMy favourite way... Pin
Florian Kruesch12-Jul-08 11:54
MemberFlorian Kruesch12-Jul-08 11:54 
GeneralRe: My favourite way... Pin
Josh Smith12-Jul-08 17:17
MemberJosh Smith12-Jul-08 17:17 
GeneralRe: My favourite way... Pin
matelich19-Dec-08 3:30
Membermatelich19-Dec-08 3:30 
GeneralReally nice article Pin
FantasticFiasco8-Jul-08 23:14
MemberFantasticFiasco8-Jul-08 23:14 
GeneralRe: Really nice article Pin
Josh Smith9-Jul-08 1:33
MemberJosh Smith9-Jul-08 1:33 
QuestionWPF newbie question: Couldn't you use a DataTemplateSelector somehow? Pin
prendebp8-Jul-08 11:55
Memberprendebp8-Jul-08 11:55 
AnswerRe: WPF newbie question: Couldn't you use a DataTemplateSelector somehow? Pin
Josh Smith8-Jul-08 11:58
MemberJosh Smith8-Jul-08 11:58 
GeneralRe: WPF newbie question: Couldn't you use a DataTemplateSelector somehow? Pin
prendebp8-Jul-08 12:41
Memberprendebp8-Jul-08 12:41 
GeneralRe: WPF newbie question: Couldn't you use a DataTemplateSelector somehow? Pin
Josh Smith8-Jul-08 15:33
MemberJosh Smith8-Jul-08 15:33 
GeneralNice. Pin
Douglas Troy8-Jul-08 5:40
MemberDouglas Troy8-Jul-08 5:40 
GeneralRe: Nice. Pin
Josh Smith8-Jul-08 5:42
MemberJosh Smith8-Jul-08 5:42 
Generalmore pictures like this in articles Pin
Quang Tran Minh7-Jul-08 21:27
MemberQuang Tran Minh7-Jul-08 21:27 
GeneralRe: more pictures like this in articles Pin
Josh Smith8-Jul-08 1:12
MemberJosh Smith8-Jul-08 1:12 
GeneralRe: more pictures like this in articles Pin
Quang Tran Minh8-Jul-08 5:10
MemberQuang Tran Minh8-Jul-08 5:10 
GeneralSo... Pin
kevdelkevdel7-Jul-08 6:33
Memberkevdelkevdel7-Jul-08 6:33 
GeneralRe: So... Pin
Josh Smith7-Jul-08 6:34
MemberJosh Smith7-Jul-08 6:34 
QuestionWhat caught my attention... Pin
Stan Alex6-Jul-08 23:19
MemberStan Alex6-Jul-08 23:19 
AnswerRe: What caught my attention... Pin
Josh Smith7-Jul-08 1:46
MemberJosh Smith7-Jul-08 1:46 
GeneralNice one Pin
Pete O'Hanlon6-Jul-08 10:38
mvePete O'Hanlon6-Jul-08 10:38 
GeneralRe: Nice one Pin
Josh Smith6-Jul-08 12:10
MemberJosh Smith6-Jul-08 12:10 
GeneralCongrats Pin
Judah Gabriel Himango6-Jul-08 9:20
sponsorJudah Gabriel Himango6-Jul-08 9:20 
GeneralRe: Congrats Pin
Josh Smith6-Jul-08 9:22
MemberJosh Smith6-Jul-08 9:22 
GeneralAnother Alternate Way Pin
CMJobson5-Jul-08 23:51
MemberCMJobson5-Jul-08 23:51 
GeneralRe: Another Alternate Way Pin
Josh Smith6-Jul-08 2:51
MemberJosh Smith6-Jul-08 2:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.