Changing the layout of a WPF TreeView to look like multiple ListBox

WPF No Comments »

Last week at work I was requested to create a new control which should have the behavior of the WPF treeview with a template involving multiple ListBox. To understand what I mean, I wanted to change the layout of this:

To this:

Of course, selection must work properly:

I asked a question on StackOverflow about this control because I didn’t find any easy way to do it. I though at the beginning that playing with the templates of the TreeView and TreeViewItem would do the trick but it didn’t.

The solution I finally choose involves creating multiple ListBox and wire them together using DataBinding:

  • I create a new CustomControl which inherits Control (I couldn’t use neither Selector or TreeView because I wouldn’t have been able to manage the SelectedItem property from the derived class)
  • In the template of this CustomControl is an ItemsControl. This ItemsControl has its ItemTemplate property set to a DataTemplate containing a ListBox.
  • The CustomControl has a Depth property of type int. This property indicates the number of ListBox that should be generated.
  • The CustomControl automatically databound ListBoxes together: each ListBox’s ItemsSource property is databound to the SelectedItem’s children property of the previous ListBox in the visual tree.
  • The CustomControl has a SelectedItem property and a SelectionChanged event (like Selector-derived class).
  • I added an IsReallySelected attached property to the ListBoxItem which are generated. This enables to databing an IsSelected property of the ViewModel class behind the control with the IsSelected of the ListBoxItem. I had to create an attached property because its value is true when the ListBoxItem is selected AND the parent ListBox has IsSelectionActive set to true.

Here is the result:

You can download the source code of this sample (VS2010 RC solution).

Minor update to the Silverlight MVVM frameworks explorer

Silverlight, WPF 1 Comment »

Thanks to the readers who gave me feedback on my Silverlight MVVM frameworks explorer I updated the application this morning in order to fix some problems.

Here is the change set:

  • fix incorrect URLs
  • fix incorrect “Silverlight Support” options. As Laurent Bugnion said in the comments, his MVVM Light framework was the only one supporting Silverlight which was strange…
  • links now open in a new window

Click on the following image to launch the Silverlight application.

About adding new frameworks, I’m not sure to add those which targets a much larger domain than MVVM itself. CompositeApplication guidance for example is a lot more than MVVM…

WPF internals part 2 : how the WPF controls are organized ?

.Net, Silverlight, WPF No Comments »

A couple of weeks ago, I started a series of articles about WPF internals organization. In the first article I did a tour of the core WPF classes. In this second part, I’m reviewing the organization of the various controls that exist in the framework.

Because the image of the diagram is pretty big, I decided to use Silverlight DeepZoom and the result is just below this text :-) You can download the full image resolution here. Please use the full screen button in the upper right corner of the viewer for the best browsing experience.

    Here are general remarks that might help you get information from those diagrams.

    The top level Control class:

    • Defines general UI properties such as Background, Foreground, BorderBrush and BorderThickness
    • Defines a set of properties to control font rendering: FontFamily, FontSize, FontStyle…
    • Has a DoubleClick event (other mouse events such as MouseUp/MouseDown comes from the UIElement class)

    Below the Control class, we have (this list is not complete):

    Below the ContentControl class we can find many existing WPF controls:

    General other remarks:

    • It’s funny to see that both Window and UserControl inherits from ContentControl. Before doing the diagram I though that Window came from somewhere else :-)
    • Having those diagrams in mind (or on a screen !) is very useful when you need to create your own custom control
    • We can see the differences between creating a custom control (inherit from Control or derived class) and a UserControl (inherit from UserControl)
    • .Net4 will introduce new controls (not in this diagram) in the WPF framework such: DataGrid, Calendar, TimePicker

    kick it on DotNetKicks.com

    Discover and compare existing MVVM frameworks !

    .Net, Silverlight, WPF 12 Comments »

    A couple of weeks ago, I wrote a blog post where I compared the existing MVVM frameworks. This post became a bit famous in the WPF/Silverlight blog world and I received a lot of feedback to update the list, fix information, etc. I also got a request from Erik suggesting me to put all the datas in a matrix.

    Today I’m proud to announce the MVVM frameworks Silverlight application (click the image to open the Silverlight3 page).

    silverlight-mvvm-app

    A couple of observation:

    • please contact me via this blog or twitter if you find incorrect information
    • I’m not judging anybody’s work by giving rating, it’s just my personal feeling to have an easiest way to sort the data

    Hope you’ll like it :-)

    PDC09 : How VS2010 was built with WPF ?

    .Net, Events, Tools, Visual Stutio, WPF No Comments »

    PDC09

    In my last blog post, I did a review of a PDC09 Session “Advanced performance tuning with WPF”. Today, I’m doing a review for another very interesting session “How VS2010 was built with WPF ?”. The video is available here.

    vs2008tovs2010

    Why did Microsoft choose WPF for VS2010 ?

    • Technological: prove the capabilities of WPF4
    • Architectural
      • Separated presentation
      • Support for long range road map (+10 years)
    • Key VS2010 features need it: Editor, Architecture Editor, Parallel tools debugging
    • Take an opportunity to give feedback for WPF4: when VS2010 development started, .Net 3.5 SP1 was just shipped and it was the right time to give feedback for the new features and fixes for WPF4.

    It is worth noting that VS2010 is a project that is being watched carefully inside Microsoft. We can expect that more Microsoft applications will move to WPF in the next coming years.

    What WPF features are used ?

    • Declarative UI using XAML
    • Databinding
    • Styles and templates
    • Application Resources
    • Interop Win32 (because they did not have the time to rewrite everything using WPF or because features doest not need to use WPF for example de WinForms designer…)
    • Integration with the message loop (to deal with particular focus issues)
    • New text stack (part of WPF4) based on DirectWrite

    Staged approach

    • Define data models: a huge diagramming and architectural exercice
    • Replace the main window with WPF (only the window not its content !) to start the mix approach (managed/unmanaged, WPF/Hwnds)
    • Write new managed components: Window manager, command bar presentation
    • Scout with other VS teams
    • Test, Test, Test…

    What were the challenges ?

    • Mixed mode application: native and managed code; WPF and HWNDs (Win32 or WinForms)
    • Keep existing extensions working and allow new extensions to take advantage of WPF
    • Don’t “stop the train” other teams were working at the same time on the product to add new functionalities
    • Text clarity
    • Performance
    • Focus management

    You can watch the session here if you want more detail and demos of what I mention in this post.

    PDC09: Advanced WPF Application Performance Tuning

    Events, WPF 2 Comments »

    PDC09

    In this post, I’m doing a review of the Advanced WPF Application Performance Tuning session of PDC09.

    1. Introduction

    WPF = Designer + Developer:

    • Designer: Resources constraints, Drawing effects, Excessive use of images, “Rich” template
    • Developer: Loaded modules, Startup time (cold and warm time), Memory leaks (it’s not because we have a GC that leak doesn’t exist), Large element count

    Performance general truth:

    • Measure, measure, measure (identify key scenarios and set clear goals)
    • Low hanging fruit: identify parts that need optimized (to avoid spending time on optimizations that will not be perceived by the user)
    • Perceived performance is the most important thing: make it feel fast
    • Trade-offs: CPU vs memory…

    After this short intro, the speaker introduce FishBowl a sample WPF application that brings Facebook on our desktop. This app will be used as a reference in the rest of the session to demonstration optimization techniques.

    fishbowl

    2. Memory usage

    The demonstration starts using Process Explorer to have a look at the memory usage of the app which is about 150MB. This seems quite high for such an application. By using VMMAP, the speaker finds out that the native heap is 100MB whereas the managed heap is only 50MB. This seems strange for a pure WPF application.

    There is always native heap (render thread…), but when it’s particularly large, it’s generally related to images used in the application.

    By browsing the source code of FishBowl, the speaker shows that the startup animation is not XAML based but uses more than 100 PNG images holding more than 30MB of memory (that will be in the native heap).

    Using .Net memory profiler, the speaker finds out that the bitmap images used in the startup animation are not released when the animation is over causing a memory leak.

    3. Cold Start

    Cold start is all about disk I/O, we must minimize the amount of data that must be read from disk. The speaker shows that System.Window.Forms and System.Drawing assemblies are loaded during startup whereas it should not be the case for a pure WPF app (and about 300ms could be saved).

    Then using the “Show hierarchical” feature of the .Net memory profiler, he finds out that System.Drawing only has 1 instanciated type (the Rectangle class !). By changing the code to remove those dependencies he prevents those 2 DLLs from loading in the startup process and improve the startup time !

    Although by changing this code:

    ?View Code CSHARP
    1
    2
    3
    4
    5
    6
    
    if(Properties.Settings.Default.EnableLoggin)
    {
      // LogEntry is defined in the Entreprise Logging Library DLL
      // and use this class will cause the assembly to be loaded
      var entry = new LogEntry();
    }

    Into this one:

    ?View Code CSHARP
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    if(Properties.Settings.Default.EnableLoggin)
    {
      // the previous code has been moved to a dedicated method
      this.LogMessage();
    }
     
    [MethodImpl(MethodImplOptions.NoInlining]
    private void LogMessage()
    {
      // code that uses LogEntry and needs to load the Loggin assembly
    }

    We can prevent the DLL from being loaded when the loggin option is not enabled ! Notice the MethodImpl attribute that prevents the compiler from inlining the method (which would take us back to the original code…)

    4. Warm start

    During warm start we’re not expecting to see as much I/O as during cold start. The first tool that should be used to analyze warm start is a CPU profiler.

    In the FishBowl app, the main ListBox does not have virtualization turned on because each item has a variable height which cause a hang in the startup process. In order to improve the experience of the user, the app has been updated to load the elements in a background thread.

    The real performance is not changed here, but the perceived performance for the user is much better because he has a visual feedback instantly !

    5. RunTime

    Using WPFPerf, it’s possible to find out what the CPU usage is (between animation, layout, rendering…). The perforator tool gives various graphs such as Frame Rate, Software and Hardware IRTs (Intermediate Render Target).

    Currently if a Rectangle has DrapShadowEffect with an Opacity of 0, it is still computed by the rendering thread (it could be an optimization that WPF does internally but it’s not yet the case) which can cause performance issue when the parent item is animated.

    A possible optimization is to split the Rectangle into 2 Rectangles:

    • the first one with the effect and an opacity of 0 (on the Rectangle itself not on the effect like previously)
    • the second one without any effect and an opacity of 1 (visible), a storyboard is set on this rectangle to make the first element visible by animating its opacity

    In this case, because the first Rectangle is hidden (Opacity = 0), the cost needed to animate this rectangle is much better.

    Aditionnal recommendations:

    • don’t block on the UI thread
    • use virtualization, if you can’t use it, improve the perceived performance by loading the items in a background thread
    • data virtualization
    • freeze your freezable !

    6. Summary

    • Memory: images size, memory leaks, elements count
    • Cold start: disk I/O, module loads, NGen
    • Warm start: avoid blocking, delay work, perceived perf
    • RunTime: beware of IRTs, eventing

    7. Tools

    • Process Explorer in order to know how much memory has been allocated
    • VMMap where the memory is going ? (native head, managed heap…)
    • .NET memory profiler the profiler that is being used by the WPF team internally at Microsoft
    • ETW: event tracing
    • WPFPerf: WPF performance analyzer

    PDC09: some WPF sessions are available !

    Events, WPF No Comments »

    PDC09

    Earlier today, I mentioned that PDC09 videos will be available soon.

    The first WPF videos are now available ! This article will be updated once new videos become available:

    • How Microsoft Visual Studio 2010 Was Built with Windows Presentation Foundation 4 [VIDEO HERE]
    • Advanced Windows Presentation Foundation Application Performance Tuning and Analysis [VIDEO HERE]
    • Mastering WPF Graphics and Beyond [VIDEO HERE]
    • Windows Presentation Foundation 4 Plumbing and Internals [VIDEO HERE]
    • XAML Futures in Microsoft .NET Framework, Microsoft Silverlight and Tools [VIDEO HERE]

    How to measure rendering time in a WPF application ?

    WPF 1 Comment »

    Last week, a colleague of mine asked me an interesting question: “I’m filling a control with content and I’d like to measure the time needed to render my control. How can I do that ?”

    The first approach is to measure the elapsed time needed to instantiate and populate the control from C# code. We can use the StopWatch class to have a precise and easy to use measuring tool.

    ?View Code CSHARP
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    Stopwatch sw = new Stopwatch();
    sw.Start();
     
    for (int i = 0; i < 5000; i++)
    {
      // here is the operation that fills the control
      this.canvas.Children.Add(new Rectangle());
    }
     
    sw.Stop();
    MessageBox.Show("Took " + sw.ElapsedMilliseconds + " ms");

    However this approach will not give good results because we’re not taking into account the time needed to render elements in the visual tree. This is because elements are not rendered when you call the Add methods (for example in a Canvas) but when the visual tree is fully loaded.

    A much better approach is to use the Dispatcher and request it to process an action at a priority right bellow the Render priority which is the Loaded priority:

    dispatcherpriority

    Using this trick, we ensure that all rendering actions have been completed. We can use the following code to do that:

    ?View Code CSHARP
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    Stopwatch sw = new Stopwatch();
    sw.Start();
     
    for (int i = 0; i < 5000; i++)
    {
      // here is the operation that fills the control
      this.canvas.Children.Add(new Rectangle());
    }
     
    this.Dispatcher.BeginInvoke(
      DispatcherPriority.Loaded,
      new Action(() =>
      {
        sw.Stop();
        MessageBox.Show("Took " + sw.ElapsedMilliseconds + " ms");
      }));

    Hope this helps !

    WPF internals part 1 : what are the core WPF classes ?

    .Net, WPF 4 Comments »

    In this first article, I’d like to make a tour of the core WPF classes and how they are related.

    Knowing the organization of WPF classes is important when we create a new control because we have to determine which base class we’re going to use. It is also interesting to know how the framework has been designed. That’s the goal of this first article.

    Here is an image of the core WPF classes and how they are related (click for larger resolution):

    The diagram is voluntary simple above the Control classes because that will be targeted by another article.

    The top level class DispatcherObject:

    • represents an object that is associated with a Dispatcher
    • can be accessed from a thread other than the thread the DispatcherObject was created on, using Invoke or BeginInvoke calls
    • can enforce thread safety by calling VerifyAccess
    • cannot be independently instantiated; that is, all constructors are protected

    From the DispatcherObject class, we have 4 new classes (one more time, this is a partial view of what really is in the framework):

    The DependencyObject class:

    • contains the mechanism to deal with Dependency Properties through a set of methods such as ClearValue, SetValue and GetValue
    • is inherited by 3 new classes
      • TriggerBase, for specifying a conditional value within a Style object. Inherited by DataTrigger, EventTrigger
      • Freezable, for object that has a modifiable state and a read-only (frozen) state. Classes that derive from Freezable provide detailed change notification, can be made immutable, and can clone themselves
      • and the Visual class,

    The Visual class:

    • provides rendering support in WPF, which includes hit testing, coordinate transformation, and bounding box calculations
    • is the first class supporting the VisualParent property that helps setting up the visual tree
    • support methods for adding, removing and getting visual child (through the IAddChild interface)
    • has an VisualEffect property of type Effect (from Animatable / Freezable)
    • is inherited by the UIElement class,

    The UIElement class:

    • can render as a child element
    • contains logic that is used to size and position possible child elements of a UIElement (when interpreted by a layout system)
    • can respond to user input (including control of where input is getting sent to via their handling of event routing, or routing of commands)
    • can raise routed events that travel a route through the logical element tree
    • supports some aspects of the animation system
    • is enhanced by the FrameworkElement class,

    The FrameworkElement class extends the UIElement class by adding the following functionalities:

    • layout system definition using the ArrangeOverride method
    • logical tree with the Parent property
    • object lifetime events such as Initialized, Loaded, Unloaded
    • support for databinding (DataContext property) and resources management (Resources property)
    • support styles (Style property)
    • does not handle the Template feature implemented in the Control class

    Several classes inherit the FrameworkElement class:

    The Control class:

    • is the base class for WPF controls that use a ControlTemplate to define their appearance (through the Template property)
    • defines a set of UI properties (that can be exploited by ControlTemplates): Background, BorderBrush, BorderThickness, FontFamily, FontSize, FontStrech, FontStyle, FontWeight, Foreground and Padding
    • support mouse double clicks event using MouseDoubleClick and PreviewMouseDoubleClick

    In order to show where most of the WPF controls are (but that will be the object of another article), I also added ContentControl, ItemsControl, UserControl and Window class to the diagram.

    Announcing the “WPF internals” series

    .Net, General, WPF No Comments »

    I’m starting a new series of article I’m calling “WPF internals” where I’ll be reviewing how things works <inside> WPF. I haven’t the entire content yet, but here is a summary of what I’m planning to do:

    • Part 1 of N: what are the core WPF classes ?
    • Part 2 of N: how the WPF controls are organised ?
    • Part 3 of N: how ZIndex works ?
    • Part 4 of N: how InputGestures works ?
    • Part 5 of N: how databinding with DataContext works ?
    • Part 6 of N: how databinding with an ItemsControl works ?
    • Part 7 of N: what is the difference between a ContentControl and a ContentPresenter ?

    I setup a new page in the header so that links are easy to access.

    All the information that I’m going to give here is based on my PERSONAL understanding using tools like Reflector and VS Class Diagram Designer that help me figure out how things fit together. I’m neither a Microsoft WPF Architect nor a Program Manager on the .Net framework !

    Please let me know if you’re interested in special topics, I’ll do my best to try to include them in the series. Please also feel free to leave comments on the articles so that if I’m misunderstanding something I can fix it.

    I hope to post the first article this week (before October, 16th)

    WP Theme & Icons by N.Design Studio
    Entries RSS Comments RSS Log in