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.

    Using Snoop to take a look at VS2010 !

    .Net, Visual Stutio 5 Comments »

    If like me you’re curious about how big WPF applications are made, you probably tried to use Snoop to inspect the visual tree of Visual Studio 2010 Beta2. And you probably had a problem because Snoop wasn’t able to detect the devenv process of VS2010:

    I wasn’t sure about the cause of this problem, but I grab the source of Snoop and took a look at the code that list the available window:

    ?View Code CSHARP
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    public void Refresh() {
    	this.windows.Clear();
     
    	foreach (IntPtr windowHandle in NativeMethods.ToplevelWindows) {
    		WindowInfo window = new WindowInfo(windowHandle, this);
    		if (window.IsValidProcess && !this.HasProcess(window.OwningProcess))
    			this.windows.Add(window);
    	}
     
    	if (this.windows.Count > 0)
    		this.windowsView.MoveCurrentTo(this.windows[0]);
    }

    I setup a breakpoint to find out what was wrong and discover that the window.IsValidProcess failed with the VS2010 process. Because I just wanted to check if it was the only reason why Snoop wasn’t able to inspect it, I hack the code to remove this test:

    ?View Code CSHARP
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    public void Refresh() {
    	this.windows.Clear();
     
    	foreach (IntPtr windowHandle in NativeMethods.ToplevelWindows) {
    		WindowInfo window = new WindowInfo(windowHandle, this);
    		if (/*window.IsValidProcess &&*/ !this.HasProcess(window.OwningProcess))
    			this.windows.Add(window);
    	}
     
    	if (this.windows.Count > 0)
    		this.windowsView.MoveCurrentTo(this.windows[0]);
    }

    And it’s working:

    vs2010-snoop

    Happy exploration with Snoop :-)

    VS2010 Beta 2 coming today !

    .Net, Visual Stutio No Comments »

    In case you don’t have the info yet, VS2010 Beta2 is coming today October 19th for MSDN subscribers. It will be released to public on Wednesday (source).

    Also, Visual Studio 2010 RTM will officially launch on March 22, 2010

    vs2010

    I’ll try to give some feedback as soon as I’ll be able to grab my copy and install it on ma workstation !

    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.

    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 !

    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)

    The cost of building Visual Trees

    .Net, WPF No Comments »

    In the current project I’m working on, I’m designing a diagramming component. Of course because it’s for work I can’t release the source code (however if you want a good starting point you can check out this article). Designing such a component is a challenging task and there are a number of things I learned during the last few months that I’m glad to share here.

    As you problably know the WPF engine manages 2 trees: the logical tree and the visual tree. For each logical item (that you declare in the XAML), the item is expanded with its visual tree (for example, a scrollbar is made of RepeatButtons and a Thumb). To visualize the visual tree you can use a tool like snoop.

    In a diagramming tool, you might want to draw lines betweeen entities, like the following:

    connection

    In this article, we’re going to talk about the underlying control that we can use to do that. If you need to create that kind of control, you basically have 2 options:

    • inherits from Control and override the OnRender method to do the basic graphic operations (such as drawing a line or an ellipse)
    • inherits from Control and create a ControlTemplate to fill the visual tree of your control

    Of course the first option has better performance, but it’s also less evolutive. Moreover, in the OnRender method, you can only do low level graphic operations.

    Using the second option is generally fine and easy:

    1. create the class that inherit from Control
    2. create a style that targets your new control
    3. add a Setter to set the ControlTemplate property
    4. fill the ControlTemplate’s content

    Here is a sample ControlTemplate for a basic connection (assuming that the Connection class has 4 double dependency properties (X1,Y1) (X2,Y2) that defines that start and the end point):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    <Style TargetType="{x:Type VisualTreePerf:Connection}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type VisualTreePerf:Connection}">
              <Line X1="{TemplateBinding X1}" Y1="{TemplateBinding Y1}"
                      X2="{TemplateBinding X2}" Y2="{TemplateBinding Y2}"
                      Stroke="Black" StrokeThickness="2">                                
              </Line>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>

    Of course this is a very minimal template, you’re probable going to improve it by adding new features:

    • 2 rectangles to show the extremities of the connection
    • 2 thumb to be able to drag’n'drop the extremities
    • 1 context menu to access connection’s operations

    You can do that by adding more controls to the template. Now, take a second and think about the performances. Time is needed to built and render the visual tree and the most complex it is, the longer it takes. I did a quick benchmark on my machine and here are the results for 500 connections added in a Canvas:

    performance

    What we can see is that adding only 5 controls in the template, we multiply the rendering time by 4 ! That means we must be careful when we’re designing ControlTemplate that are going to be instantiated many time. Before creating the control we should think about whether the control is going to by displayed 1, 10, 100 or 1000 times in our application. More complex ControlTemplates mean more time to render them. Several techniques can be used to improved performance:

    • use a panel that supports UI virtualization (such a VirtualizingStackPanel)
    • use adorners to give feedback while an item is selected to improve creation performance (create the Adorner only when the item is selected)

    To explore other performance related techniques:

    A quick tour of existing MVVM frameworks

    .Net, WPF 27 Comments »

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

    Read the rest of this entry »

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