Tag Archives: WPF

Set up the main window of your WPF project

Intro: In this post, I’m exploring various techniques we can use in order to have a custom Window in a WPF project.

Today you start a new application. You open Visual Studio, “File”, “New”, “Project”, “WPF Application” and you start typing code… At some point, you might want to tune the main window of your application in order to have a custom header. The most common reason to do so is when you want to render some UI elements outside the standard client area of a window:

For example in order to have something similar to Office 2010 (with icons inside the Window’s header):

Also, you want to make sure you application works also great on Windows XP. This is probably not your personal choice but some guy from the marketing told you: it MUST runs on XP 🙂

Let see what are the various options you can choose

Option1: use the WindowStyle = None option on the “standard” WPF Window

  • How to do?

In the XAML (or in the C# code), simply set the value of the WindowStyle property of your Window to None:


  • How does it look on Window XP ?

  • How does it look on Windows 7 ?

  • Advantages

– Same solution for Windows XP and Windows 7.

– The client area now occupies the whole Window. We are then able to render elements at the top of the Window in order to re-create the standard window header.

– Very simple to use (minimal changes in your code).

  • Drawbacks

– A lot of work is needed to create the actual header: show the title of the Window, its context menu and the standard window buttons (Minimize, Restore, Close)

– Several problems appears when the Window gets maximized:

The Window occupies the whole screen and hide Windows’s taskbar. You need some interop code to change the MaxHeight/MaxWidth of the Window. You can see this post for more details: Maximizing window (with WindowStyle=None) considering Taskbar

Even though you fix the previous problem, the border of the window is still visible when it gets maximized:

Option2: use Option1 + ResizeMode =NoResize in order to remove the remaining border

You can easily fix the previous problem by registering an event handler on the StateChanged event of the Window. In the event handler, you can set ResizeMode to NoResize (when the Window is maximized) so that the remaining border disappear.

  • How to do?

In the constructor of the Window, you can add the following code:

this.StateChanged += (s, e) =>
{
    if (this.WindowState == WindowState.Maximized)
        this.ResizeMode = ResizeMode.NoResize;
    else
        this.ResizeMode = ResizeMode.CanResize;
};
  • How does it look on Window XP ?

  • How does it look on Windows 7 ?

  • Advantages

– Same solution for Windows XP and Windows 7.

– You fixed the previous issue easily.

  • Drawbacks

– No special drawbacks.

Option3: use Option2 + AllowTransparency = True

By using Option1 or Option2, you can have a much bigger client area than with a traditional Window. However, you still miss the glass effect or Aero. You might try to get this effect by adding transparency to your Window. The way to do so in WPF, is simply to set the value of the AllowTransparency property to true. Note that enabling transparency on the Window imply setting WindowStyle to None.

  • How to do?

You can use the following XAML code:


  • How does it look on Window XP ?

  • How does it look on Windows 7 ?

  • Advantages

– Minimal changes in your existing code

  • Drawbacks

– On Windows 7, you’ll have to do some serious work in order to have the DWM Blur effect (you might need to combine some shaders effects…)

– On Windows 7, you lost the drop shadow of your Window

– You might get into performance issues by turning on this option.

For more details, you can check out this MSDN blog post “Transparent Windows in WPF“:

“The performance of WPF’s transparent windows is a topic of much concern.  WPF is designed to render via DirectX.  We do offer a software rendering fallback, but that is intended to provide a full-featured fallback, not for high performance.  The layered window APIs, on the other hand, take a GDI HDC parameter.  This causes different issues for XP and Vista.

Experience suggests that a full-screen constantly updating layered window on good XP machine can consume as little as 3% CPU in overhead.

Experience suggests that a full-screen constantly updating layered window on good Vista machine can consume as much as 30% CPU in overhead.”

Option4: use interop achieve the same effect as Option2 but without having to set AllowTransparency to true

As we just saw, using adding transparency to a WPF window by using the AllowTransparency property does not look the good way to go. In this last section, we’re going to see another way using Windows native APIs.

The APIs we’re interested in are in the DwmApi.dll library. Here is the associated MSDN documentation:

DwmExtendFrameIntoClientArea s the DWM function that extends the frame into the client area. It takes two parameters; a window handle and a MARGINS structure. MARGINS is used to tell the DWM how much extra the frame should be extended into the client area.

To use the DwmExtendFrameIntoClientArea function, a window handle must be obtained. In WPF, the window handle can be obtained from the Handle property of an HwndSource. In the following example, the frame is extended into the client area on the Loaded event of the window.

Using this API, you can achieve this kind of effect without having to use the AllowTransparency (on Vista or 7 only of course):

On Windows XP, you don’t have DWM and then you’ll not be able to have the glass effect. However, you can still extend the client area of your Window using some other Windows native API.

The easiest way to do all this work is to use the WPF Shell Integration Library, available on CodePlex:

The custom chrome feature allows applications control over the outer frame of the window so that WPF content can be drawn over the title bar. This allows applications to integrate with Aero glass to emulate the Office 2007/2010 look and feel, or to completely replace the frame with its own content without having to manage all the system behaviors that get lost when using WindowStyle.None.

This project also contains Windows 7 taskbar features (those features are now directly integrated in the .Net framework 4.0).

  • How to do ?

You have to setup 2 distinct styles for Windows 7 and Windows XP. You can tweak them but here is the general organization of those styles:

On Windows XP:


As you can see, on Windows XP, you have to create the minimize/restore/close buttons yourself.

On Windows 7:


  • How does it look on Window XP ?

  • How does it look on Windows 7 ?

  • Advantages

– No performance issue since AllowTransparency is not used

– On Windows 7 the header looks like standard OS windows

  • Drawbacks

– You have 2 distinct solutions for Windows XP and Windows 7. On Windows XP, you have to add the Window’s buttons manually (reduce, maximize, close)

– You must rely on a new assembly Microsoft.Windows.Shell. However, if you don’t want to, you can import the source code in your project: the features are dispatched in two .cs files and released by Microsoft under the MS-PL License.

Conclusion

In any WPF application, the Windows frame itself matters. If you want to render graphical elements outside the client area, you must be careful. You basically have 2 options:

– stick to managed code only and use the AllowTransparency property. However, you must be aware of potential performance issues. Also, you’ll need to do a lot of work on your own.

– use Window native APIs. You’ll have to distinguish Windows OS which have DWM (Vista and 7) and XP. You’ll have optimal performance. The easiest way to do is to use the Shell Integration library project.

Interesting Links

A WPF behavior to improve grouping in your ListBox

Post updated Jan. 2nd 2014 to fix a bug when items have a background.

A couple of weeks ago I started prototyping with a friend a behavior in order to improve the grouping in the ListBox control. Today, I’m finally taking time to write a post about this adventure 🙂

My overall goal was to have the group headers always visible and smoothly moving while the content of the control was scrolled. Here is a video showing the demo application running:

[flashvideo file=http://www.japf.fr/wp-content/uploads/2010/11/OverlayGroupingBehavior.mp4 /]

Download the code (VS2010 required)

Of course I wanted to have the cleanest implementation possible, and as I think you already know, this where the WPF behavior comes to the rescue ! Let’s see how this is possible.

Note:

  • You must be aware that enabling group in your ListBox will disable UI virtualization. This might not be a problem if the databound collections is small (<100/200) but if the collection is very large, you might get into performance problem. However this limitation might be fixed in the next release of WPF (see my post about it here).
  • This solution is not 100% compatible with keyboard selection and should be improved to work properly.

Anatomy of a ListBox when grouping is enabled

In order to create this behavior, I had to carefully look the Visual Tree of a ListBox when grouping is enabled. I used Snoop to do so, and I was able to get the following picture:

As you can see, for each group, we have a GroupItem control. However, we cannot direcly apply a transform to this element because it both contains the header (in a ContentPresenter) and the items in the group (in an ItemsPresenter).

Introducing the OverlayGroupingBehavior

The behavior actually walks in the visual tree to find out the interesting part. In our case, we want to attach a TranslateTransform to the headers of each GroupItem. Then, using simple mathematics, we can figure out the needed Y-translation to move the header at the top position of the ListBox.

Here are some details about the behavior:

  • the class inherits Behavior<ListBox>
  • we override the OnAttached method, and in this method we register an event handler for the LayoutUpdated of the associated ListBox
  • in the LayoutUpdated handler, we update the transforms
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using DemoAnimatedGroup.Helpers;

namespace DemoAnimatedGroup.Behaviors
{
    public class OverlayGroupingBehavior : Behavior
    {
        protected override void OnAttached()
        {
            this.AssociatedObject.LayoutUpdated += new EventHandler(this.OnLayoutUpdated);
        }

        private void OnLayoutUpdated(object sender, EventArgs e)
        {
            ListBoxItem topListBoxItem1;
            GroupItem topGroupItem1, topGroupItem2;
            ContentPresenter topPresenter1, topPresenter2 = null;
            double topOffset1, topOffset2 = -1;

            // find the first ListBoxItem which is at the top of the control
            topListBoxItem1 = this.GetItemAtMinimumYOffset();
            if (topListBoxItem1 == null)
                return;

            // get all group items order by their distance to the top
            var groupItems = TreeHelper.FindVisualChildren(this.AssociatedObject)
                                       .OrderBy(this.GetYOffset)
                                       .ToList();

            // from the GroupItem, find the ContentPresenter on which we can apply the transform
            topGroupItem1 = TreeHelper.FindVisualAncestor(topListBoxItem1);
            topPresenter1 = TreeHelper.FindVisualChildren(topGroupItem1).First(cp => cp.Name == "PART_GroupHeader");
            topOffset1 = this.GetYOffset(topPresenter1);
            
            // try to find the next GroupItem and its presenter
            var index = groupItems.IndexOf(topGroupItem1);
            if (index + 1 < groupItems.Count)
            {
                topGroupItem2 = groupItems.ElementAt(index + 1);
                topPresenter2 = TreeHelper.FindVisualChild(topGroupItem2);
                topOffset2 = this.GetYOffset(topPresenter2);            
            }
                       
            // update transforms
            if (topOffset2 < 0 || topOffset2 > topPresenter1.ActualHeight)
                this.SetGroupItemOffset(topPresenter1, topOffset1); 

            if(topPresenter2 != null)
                topPresenter2.RenderTransform = null;
        }

        private T GetItemAtMinimumYOffset() where T : UIElement
        {
            var minOffset = double.MaxValue;
            T topItem = null;
            foreach (var item in TreeHelper.FindVisualChildren(this.AssociatedObject))
            {
                var offset = this.GetYOffset(item);
                if (Math.Abs(offset) <= Math.Abs(minOffset))
                {
                    minOffset = offset;
                    topItem = item;
                }
            }

            return topItem;
        }

        private void SetGroupItemOffset(ContentPresenter groupHeader, double offset)
        {
            if (groupHeader.RenderTransform as TranslateTransform == null)
                groupHeader.RenderTransform = new TranslateTransform();

            ((TranslateTransform)groupHeader.RenderTransform).Y -= offset;
        }

        private double GetYOffset(UIElement uiElement)
        {
            var transform = (MatrixTransform) uiElement.TransformToVisual(this.AssociatedObject);
            return transform.Matrix.OffsetY;
        }
    }
}

Using the behavior

It's more than easy to enable this functionality in any existing app. In the XAML, all you have to do is to attach the behavior to the targeted ListBox:


    
        
    
    
        
            
        
    
    
        
        
        
    


If you're not already grouping items in your ListBox, here is how to do it:

var cv = CollectionViewSource.GetDefaultView(viewmodel.Cities);
cv.GroupDescriptions.Add(new PropertyGroupDescription("Country"));

Useful resources

Download the code (VS2010 required)

[PDC10] WPF vNext

Day 1 of PDC 2010 is now over and I had the chance to watch the “WPF vNext” session by Rob Relyea. You can follow this link if you want to watch the video on-demand.

History

Rob starts with an history of Microsoft products from Windows 95 and IE 1.0…

The Blend team was created to build tools that would meet developers and designers needs. They worked closely with the Avalon team (codename for WPF) to make sure the platform was adequate and toolable.

Then the Cider team started their work in order to have a good integration in Visual Studio.

At this point, .Net 3.0 hasn’t shipped yet (it was in 2006), but Microsoft already has the vision of having XAML-based technology in the browser (with what would become Silverlight) and on the phone.

Silverlight & WPF

Silverlight

  • focuses on premium media experiences and business applications
  • suitable for most other types of application

WPF

  • complex ISV (Independent Software Vendors) applications
  • key scenarios includes DX and Hwnd interop

Convergence

  • bringing key features of WPF into Silverlight
  • WPF will support Silverlight hosting in the next version

ISV needs

  • great Windows applications
  • modern UI
  • seamless integration
  • rich content

Microsoft adoption of WPF

  • Visual Studio 2010
  • Expression Studio
  • Web Matrix
  • Powershell ISE
  • more to announce from Microsoft, but not during this PDC…

WPF vNext

  • integration of the Ribbon in WPF
  • improved collections handling in background thread (simplify the problem related to the UI thread)
  • improved UI virtualizing and grouping (right now virtualization is disabled as soon as you group data in an ItemsControl)
  • seamless integration: new SilverlightHost control (so we’ll be able to have DeepZoom in WPF !)
  • hwnd-based will no longer have airspace problem (for example, a Winforms control is always rendered on top of all other WPF controls).

As a conclusion, it’s good to see Microsoft finally giving some information about the future of WPF. The most important part I guess is to understand that Microsoft is still doing improvements on WPF and positioning WPF as the key technology for building apps with modern UI on Windows. We might have more and more applications switching to Silverlight but I’m sure they are still a lot of need for a technology like WPF which can use the whole power of the Windows OS (wheter it’s interop with native code, DirectX or other technologies).

For more information, you can also check-out a blog post from Pete Brown entitled “The Present and Future of WPF“.