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

    Review of 2009 blog posts

    General No Comments »

    In the past year, I’ve posted more than 30 articles on my blog. Here is a summary of those posts (link in bold are those which got the most traffic during the year). Obviously, MVVM was a very hot topic during 2009 :-)

    January

    February

    March

    April

    May

    July

    August

    September

    October

    November

    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 5 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.

    Analyzing events usage using a R# plugin

    .Net, Tools 4 Comments »

    As you might already know, even if the .Net framework has a garbage collector, you can easily create memory leaks in your application.

    The most common way to create a leak is to register to an event handler on a object that has a longer lifetime than the object where the handler is defined. The problem can also occurs by using static class such as EventManager (for more information see this blog post). Some .Net developers have been working on a way to go round the problem using Reflection, Weak Reference and other cool stuff. You can check out for example this excellent article on Code Project.

    However, if you cannot change the way your declare events (because of internal policies in the company or because you don’t have the source code), you must be very carefull about the way you manage your events.

    I’ve been working lately on a Resharper plugin that helps detecting events that are never unsubscribed. Basically, what is does is the following:

    resharper_plugin

    I’d like to have feedback from you .Net developpers, about whether you find such a plugin useful or not.

    • How do you deal with the event memory leak problem ?
    • Would you like to use my plugin ?
    • Would you like me to release it on a open source platform ?
    • What other kind of possible leaks are you thinking about to enhance the plugin ?

    Please write a comment to let my know what you think. Thank you for your feedback !

    A quick tour of existing MVVM frameworks

    .Net, WPF 30 Comments »

    [Article updated november, 26th: see my latest blog post for a better experience browsing the frameworks]

    Read the rest of this entry »

    Learn how .Net manages memory in 15min

    .Net 1 Comment »

    A couple of days a ago I colleague sent me a cool link that I wanted to share here.

    If you want to learn how .Net manages memory in details, understand how the garbage collector works,  what is the next object pointer, how finalizers are managed (and much more !), you should check it out this cool video made by the guys of ANTS Profiler:

    memory-management

    source video

    Visual Studio 2010: Beta1 available with .Net4 and WPF4 included

    Visual Stutio 2 Comments »

    In case you missed it, Beta1 of Visual Studio 2010 has been announced yesterday.

    vs2010

    Since monday it is available to all MSDN subscribers, and will be avaible to the rest of the world on wednesday. Documentation has also been updated to show the new features of this release.

    The download is on its way and I’ll try to post feedback as soon as I can, stay tuned !

    Browse your codebase like a pro with ReSharper

    Tools, Visual Stutio No Comments »

    I’ve already blogged about R# a couple of times. There is no doubt: it’s a must have for any serious .Net developper. A few weeks ago I learned and setup new shortcuts to improve my navigation skills in Visual Studio.

    Here are the results… If I want:

    • to find a Type I hit Ctrl+T
    • to find a File I hit Ctrl+Shift+T
    • to find a Member (in a file) I hit Ctrl+Alt+T (Note: I setup this one on my own using Tools/Options/Keyboard)

    A search box opens and I can start searching instantaneously.

    resharpernavigation1

    Here are the basic scenarios :

    • I want to open the ViewModelBase class, I hit Ctrl+T and then VMB (R# is able to search using capital letters)
    • I want to go to the OnPropertyChanged, I hit Ctrl+Alt+T and then OPC (same as previous example)
    • Finally, to open the file in the Solution Explorer I hit Shift+Alt+L

    It’s simply amazing the time we can save using those simple shorcuts. Of course, you need to be quite familiar with your codebase (if you just arrive on a project it will be harder :p)

    The future of WPF at Mix09

    Events 1 Comment »

    mix09

    MIX09 is now over and the good news is that we can watch all sessions that have been recorded online !

    I didn’t have time yet to watch all sessions I’m interested in, but I already saw “What”s new in WPF 4″ video (available here).

    Here are the important points of this session regarding the future of WPF:

    • Lot of new things are coming in WPF4: Text clarity improved, Multi-touch, Windows7 integration, Ribbon control, Focus management improvements, Visual State Manager, Client profile, Themes, Chart controls and a lot of bug fixes
    • WPF4 will come together with .Net4 which brings its own set of cool new stuff: Dynamic Language, MEF, F#, parallel library
    • WPF will be the best choise for RAD under Windows7: Multi-touch, Taskbar integration, Ribbon, Common dialogs, File explorer customization…
    • Multi-touch support: UIElement changes to manage touch related events, touch support is added for some controls (ScrollViewer)
    • New composition API: developers can control graphical elements cached in video memory
    • Controls that are currently available in the WPF toolkit will be integrated into the platform (DataGrid, DatePicker…) – moreover an update of the toolkit has just been released
    • Developers tools are improved: VS2010 and Blend3 helps the usage of WPF (databinding support…)
    • .Net4 will come with a new XAML parser: faster, extensible, public API to manage BAML format
    • .Net4 XAML language has new XAML features: support for generics, better references by name

    I hope will see a CTP soon so that we’ll start playing with those new features :-)

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