WPF being a fairly new technology might need to communicate with the components that are made in other technologies so in this section we will have a look as to how we can communicate with other systems that are built in Windows Forms or Activex.

Mixed UI Technologies

So if our WPF application needs to use controls that were developed earlier or just merely in different technology or we need to integrate with legacy plug ins or maybe there is some stuff which is available in WPF or we are moving our application to WPF but module by module. In all these cases our application will be hybrid of WPF and other applications.

WPF and HWNDs

The only major issue in WPF is that WPF is designed differently from Win32. The major difference is in the composition of the Window i.e how different elements combine to form a Window. In a classic Win32 app the composition works by partitioning the window into different elements. It UI elements gets the ownership of the window. This portioning is tied to the Window Handle or HWND. HWND is the type that represents Window handle in User 32. So each Win32 control has its own HWND owns all the pixels in some region of the screen, whereas in WPF the composition works in different way. WPF treats the entire window as one big canvas and all the components get to paint on that. So the individual WPF components don’t get to won a region individually. SO WPF creates just one HWND to fill the entire window. If we run the tool designed to explore the window handle then we can see that WPF window has one HWND.

As you see in the image below I have run Microsoft Spy++ and as you could see the WPFInteropSample application has a HWND wrapper. So we can see that WPF has just one big HWND for the application. However Pop ups have their own HWND as they are separate top level windows.

 

WPF and HWNDs

WPF and HWNDs

Interop Not Free

You might think that using the existing components might be cheaper but that’s not the case with interop in the long run.

  • The development cost if more as you are using a mixture of technologies.
  • There might be design compromises due the limitation of using multiple technologies in application.
  • During the runtime the application memory usage will increase by using both Windows Forms and WPF in one application.
  • There can CPU costs as well.
  • Also the WPF and Winforms control only almost look alike and the difference becomes more obvious

So we should use hybrid applications with discretion.

Limitations of Interop

When WPF was being designed it was not planned to be run on older version of windows bu after lot a demand Microsoft changed that and made it available to run on Windows Server 2003 and Windows XP which was great. But to get this accomplished there were changes that were made and those led to a few limitations. The major issues are as below:

Airspace issue

This is the major issue. Just like two aircrafts cannot occupy the same airspace similarly two different technologies cannot occupy the same pixel space. The WPF window needs to partitioned so that each area can be used by WPF, Win32 or Directx. We cannot have more than one technologies rendering on the same pixel.

The directx limitation might seem strange as we know that WPF uses directx but the reason is that WPF does not want to share its directx services. In .NET 3.5 SP1 we can take the output of directx and use it as a brush in WPF. So it is possible to get the directx output into a region of the window. But still the control is with WPF and the HWND control handled by WPF

Example

Transforms

The transforms applied in WPF will not apply to other technologies even though the component of other technology may be a child of WPF content.

Events

Event bubbling does not work across technology boundaries either.

Multi-level hybrid Nesting

There are limitations on how deeply we can nest the content. We cannot host a Windows Forms Controls inside a WPF Control  that is hosted inside a Windows forms controls that is the child of the WPF window.

Airspace Issues in WPF

  • Clipping
  • Z-Order
  • Animated Objects
  • Opacity
  • Pseudo Transparency

Multiple Top Level Windows

A simple solution to all the airspace problem is to use multiple top level windows as all the airspace issues occur when Win32 and WPF components share the same window. Airspace limitations do not apply to the desktop level. So a simple solution to the Z-order problem is to put all the content that needs to go on top in a different window. This is the same way in which pop up works. It shows up on top of all the other windows and content. We can make use of layered windows introduced by windows 2000 as after that it has been possible for multiple windows to share pixel screen. Also the WPF application can make use of transparent windows (Window.AllowsTransparency).

Input Differences

Another issue in WPF interop is handling the user input as event bubbling and tunneling is tied into WPF visual tree. So if the mouse goes into the other technology elements then events won’t bubble out of it. So the properties like IsMouseOver, IsFocusWithin, etc will not return what we are looking for.

Interop Combinations

The following table show how easy or difficult the various Interop combinations are. The easiest interop to do is with Windows forms. It is slightly harder to interop with Win32 components because we are dealing with C++ code. Hosting an activeX control inside WPF is easy but vice versa is difficult. If we want to host WPF content inside HTML then it’s easy but user restrictions are applied to WPF xbap inside the browser.

Technology WPF   Inside WPF   Outside
Windows   Forms Easy Easy
Win32 Fairly Easy Fairly Easy
ActiveX Hard Easy
HTML Easy (With Limitations) Easy

 

WPF in Win32

The most important thing to do is to host the WPF content inside the Win32 because without this we would not be able to display the WPF content at all. This service is provided by the HwndSource class as it connects the WPF visual tree to an Hwnd. We can do this as shown in the code below. We just need to pass the parameters inside the constructor and then set the WPF visual tree as the root visual.

 

WPF in Win32

WPF in Win32

All the WPF content uses an HwndSource and we can retrieve this by the following code. We can get hold of the Hwdn in which the WPF content is displayed and this is useful as Win32 components require us to know Hwnd.

 

WPF in Win32

WPF in Win32

Win32 in WPF

To host the Win32 content inside the WPF we can use HwnHost and derive from it. Then overriding the methods to create, destroy window and for handling its windows messages.

 

Win32 in WPF

Win32 in WPF

HwndHost Keyboard Handling

HwndHost host has some optional overrides for dealing with keyboard inputs. If we want the keyboard accelerators to work perfectly whether inside WPF content or Win32 content then we need to override these methods.

  • TranslateAccelerator
  • TabInto
  • OnMnemonic

Message Pumps

If we are hosting WPF content in a Win32 application then we need to modify the Message Loop to provide the WPF Dispatcher with the opportunity it needs to manage the window messages. The Class ComponenetDispatcher that offers various static methods that we should call for message handling when a message arrives or when it’s going idle. Also WPF needs to know when you have entered the model state so that WPF can stop responding to UI inputs.

Note that we don’t need to do this when we are integrating Windows forms and WPF. WPF and Windows Forms collaborate to provide our application with message handling.

WPF inside Windows Forms

In the code below we can see WPF content inside a Windows Forms container. There is a class called ElementHost that derives from WindowsFormsControl class so that we can edit any windows forms user interface. Buts cild property is of type FramworkElement that allows us to host any WPF element.

Create a WPF Control Library and add the following code to the UserControl.

 

WPF inside Windows Forms

WPF inside Windows Forms

Now add a Windows Forms application to the solution and refer this control library in that project.

 

WPF inside Windows Forms

WPF inside Windows Forms

When we select the main form we see that theUserControl1 is available for us to use.

 

WPF inside Windows Forms

WPF inside Windows Forms

Just drag it on to the windows form and run the application and we can see the WPF control inside the Windows Forms application.

 

WPF inside Windows Forms

WPF inside Windows Forms

Windows Form inside WPF

Hosting Windows forms content inside a WPF application is almost identical. Instead of ElementHost we have WindowsFormsHost and this derives from framework element and we can add it to any WPF UI and its child property accepts a Windows Forms Control.

 

Windows Form inside WPF

Windows Form inside WPF

Windows Forms and Layout

While using the ElementHost or WindowFormsHost WPF does its best to bridge between the two layout engines and overall it works fine (Docking, Anchoring and Auto-Sizing). Even the scaling transform works for WindowsForm inside WPF.

Ambient Property in Windows Forms

These are like WPF inherited properties. Windows forms uses these to make sure that the foreground color, background color and mouse cursor are propagated to child controls.

WindowsFormHost and ElementHost both have a PropertyMap which they use to manage the transition back and forth between the inherited properties and Ambient properties and it works fine most of times.

If want to modify this then we can register a callback that will be called while propagation of any property across the interop boundary.

 

Any questions, comments or feedback are most welcome.

The code for this post can be found here.

 

Hey guys,

As you would all know that the building blocks of an application are controls but you need to know the layouts as well to know where and how you can place these controls? So we are going to talk about the layout panels in WPF, what are the common layout properties that are offered by WPF and we would also have a look on how to create a navigation application in WPF.

Before we go into what layout panels do WPF has to offer we need to have a look how the layout processing happens in WPF. Now it is obvious that WPF will redo the layout when the applications starts or when something changes on the layout. The layout occurs in two phases: measure and arrange.

In the measure phase WPF walks through the each element in the tree and finds out as how large each element would like to be by calling the method Measure() on each element and it also tries to provide the information as to how much space is likely to available. There are two types of layouts that gets formed: Constrained (when WPF is able to make a good guess of the space that might be available) and unconstrained (When WPF does not have a fair idea of the layout space available). Now elements are not supposed to ask about the space during the measure phase so they just return the preferred size. Also in the unconstrained phase where the size passed is infinity the elements are supposed to return the exact size they require. This sometimes also known as Size To Content.

In the arrange phase WPF calls the arrange method on each element as it now know how much space each element requires. WPF tries to accommodate each elements requirement and if the space provided is less than the controls asked then the controls will be scaled accordingly. But if the element is asking for impossible space then the elements will be cropped.

Declarative Layout

WPF wants us to specify what our requirements are and then in the background WPF does all the work to arrange the resources for it. The best part of it is that it is declarative and can be defined entirely in xaml which can be of course customized as well.

WPF layouts also have the special facilities like automatic resizing according to the space available for the layouts. It also supports dynamic changes that are made to the WPF applications like adaptations to data changes at runtime or locale changes at runtime.

Some of the common layout properties provided by all the layout controls in WPF as Margin, Padding, Horizontal Alignment, Vertical Alignment, Min/Max Width, Min/Max Height, Width, Height. These provide the consistency in the layouts in WPF.

Margin

The margin property helps us determine how much place is there around the space around the edges. Means if you do not want the control to take lesser space then it has been allocated to it so that it does just stick its border along with other controls you could use the margin.

We could specify the Margin as a single value and control will have uniform outer space around it. The unit for the margin is device independent pixels.

Margin in WPF

Margin in WPF

This means that the unit is 1/96th of an inch. So if the margin is specified as 96 pixels then the control will have a space of 1inch around it in theory but in actual this would happen if windows know the resolution of its output device, which is not the case in most cases as most of the windows pc end up in default configuration. If windows does not know the resolution then it will guesses it 96 for 1 inch across. But if windows is using large font sizes then the windows will guess that 120 pixels for 1 inch of the space. So now the WPF unit will be a little larger than the normal pixel. So this is confusing.

We could also specify the Left and Top margin or you could specify the left, top, right and bottom margin specifically.

 

Margin in WPF

Margin in WPF

Padding

The Padding property is similar to margin. As margin specifies the pace outside the control padding specifies the space between the border and content of the control. Padding is not available for all elements as it makes sense for controls that have content. Just like margin padding can be specified as a single number, left and top or explicitly for each left, top, right and bottom.

Alignment

Alignment comes into the picture when the space available for the control is more than required. We can specify the Vertical Alignment or Horizontal Alignment.

 

The default value of Vertical and Horizontal alignment is stretch. So if we specify the horizontal and vertical alignments other than stretch then the control would size to its content depending on the alignments specified.

Content Alignment

Horizontal and Vertical alignments specify how the controls uses the space provided by its container but Horizontal Content Alignment and Vertical Content Alignment determines how the content would align within the control.  Horizontal Content Alignment and Vertical Content Alignment have the same values as Horizontal Alignment and Vertical Alignment and behave quite similarly. The only difference is that it aligns the content instead of the control.

Explicit Height and Width

Most of the times the constrained or the unconstrained size provided to the element do not match your requirements so you could specify the explicit height and width for the control. If you do not want to specify the fixed width and height of then you specify the range by specifying the MinWidth and MinHeight and MaxWidth and MaxHeight.

Grid

WPF provides multiple styles of placing the controls by proving the multiple layout panels. The most flexible of these layouts is the grid. It derives from the panels and provides a row and column layout for placing the controls. For a constrained layouts we could provide the row and column to have autosize or for an unconstrained layout we can specify the specific row or column size values or have a proportional values.

Grid in WPF

Grid in WPF

You could see multiple things in the image above. The use of attached forperties in Button.

The Rows and columns are specified and the rows and columns are sized equally as we not specified any specific size which could be done by specifying the values.

We could also specify the specific height or width of a button and the grid row or columns will be resized accordingly if the space is available for the grid to incorporate the individual requirements for the controls.

 

Grid in WPF

Grid in WPF

We could also set the margin properties and see the effect of these properties within the grid.

 

Grid in WPF

Grid in WPF

You could see the star (*) values used for the height which is relative sizing use. We can have multiple elements in a grid and also elements can span multiple rows or columns. Grid is the default layout element when you create a new vs project.

GridSplitter

You can add a grid splitter to a cell and set the direction and it will resize the columns and rows when dragged.

DockPanel, StackPanel and WrapPanel

WPF also provides DockPanel, WrapPAnel and StcakPanel as a simpler layout panels to work with. There property values are shown in the image below:

 

A StackPanel provides horizontal or vertical stacking of elements whereas a dockpanel provides the alignment as Top, Bottom, Left, Fill and Right and a WrapPanel provides the stacking of elements from left to right and then to new line when the line space is finished.

Canvas

Canvas is the simplest panels. It just places the elements where to tell it to i.e. absolute positioning and will cause the elements to Size to Content. The positions are specified using the Canvas attached properties Top and Right. It can be used at places where you have something like drawing a which you do not want to resize.

ScrollViewer

Another layout control is ScrollViewer. It is not a Panel. It is a Content Control which allows putting control that won’t fit the screen. The Scroll Viewer performs an unconstraint layout and tells the control that it has as much space as it asked for. But this not the actual space, it is the virtual space and the scroll viewer performs the clip and translate transform to show the view of the content. The child does not need to know that it is being scrolled. It is sometimes useful use the scrolls. If you do not want to load the full virtual space initially as it might not be as Performatic. So if you want the control to participate in the scrolling process then if the child element inside the ScrollViewer implements IScrollInfo then the scrollviewer will stop pretending that virtual space is unlimited and will give the control to element for controlling the scrolling.

ViewBox

Like scrollviewer viewbox provides solution fit in content inside a constrained space. But unlike scrollviewer ViewBox scales the content to fit the ViewBox. ViewBox does this for any kind of content like vector graphics, bitmaps or WPF controls.

As you could see in the image below, the Canvas has fixed Width and Height. The reason is that the ViewBox needs to know whats the size of the content so that it can scale and resize it accordingly.

 

ViewBox in WPF

ViewBox in WPF

This works till do not set a stretch property on the ViewBox as it will start adding other behaviors in the ViewBox.

Windows

Window is the main compoanent of any WPF application. It is a Content Control. You can multiple styles in the Window like chrome, borderless or transparent.

There is also the Popup class that is used in Menus, DropDowns and ComboBox. It is also a content Control and can be put custom use.

The third type of Window is Navigation Window and it is slightly different form other windows. The model is quite similar to a web browser i.e. it can be used for navigation from one Page to another as it is built using the Page Class. It has back and forward buttons for navigation. If the Navigation application does not have a Window then the WPF will create the host window and host the page there and provide the navigation controls.

Windows in WPF

Windows in WPF

A frame in WPF is a control that will host the pages and provide the nested navigation area.

The code for this post can be downloaded here
Any questions, feedback and comments are most welcome.

 

Hey guys,

In this part 2 of learn WPF we are going to talk about Controls and see how these controls are different in WPF and what capabilities it provides you build a good WPF application. Also we would see how we can handle the user input using the events and commands.

Button

Let’s get started. You have already seen a Button in WPF. WPF also have a CheckBox and RadioButton. But as you could see in the image below

ButtonBase is the base class for the any button in WPF and ToggleButton is the base class for the CheckBox and RadioButton. Now its really interesting to know that the controls in WPF are divided into two namespaces : System.Windows.Controls (Contains Button, CheckBox, RadioButton) and System.Windows.Controls.Primitive (ButtonBase, ToggleButton, RepeatButton). Primitive controls are not designed in a way to be used individually but as a part of other controls. But you would see that the RepeatButton (A button that repeatedly raises its click event when it is pressed continiously) is part of the primitive namespace but still can be used individually. The reason because it is in the Primitive namespace is because in WPF it used as a part of other controls such as scrollbar.

RadioButtons are designed to be used in groups, so that only one of the RadioButton in the group is selected at a time. So when you assign the same group name for multiple radio buttons then only one of the radio buttons can be selected at a time. The grouping also works if you place all the radio buttons in one parent but if you assign a group name after that as well then then the groupname will override the parent grouping.

Content Model

As you might have seen in the Part 2 of Learn WPF that we could place just anything inside a button, like text, arbitrary content, data, etc. if type the below code into a WPF application you would see that you have placed multiple objects inside button.

 

Content Model WPF

Content Model WPF

This Content Model is available for any control in WPF. It not only supports the built in controls but also supports the custom controls that are made.

When you are adding just the text as content to the button you add an underscore before the letter which you want as the accelerated control for the button click.

 

Grouping Controls

Controls don’t have to be limited to a single piece of content, some controls have 2 content property. The base class for these controls is HeadedContentControl which has the both Header and Content property.

Expander and GroupBox derive from this Base Class. This allows them to have anything in the body and they can have anything in the header as well. To set anything as header we need to use the xaml property syntax which looks something like below:

 

XAML Property Syntax

XAML Property Syntax

This means I can place anything in header and anything in content. You can type the following code in a WPF application and see that header and content and have the same model but at the two different places.

 

Header and Content

Header and Content

Text Input

WPF has 3 controls for Text Input.

  • TextBox – This takes only input text as string and does not support any formatting.
  • RichTextBox – Allows formatting of text. Although you might be surprised to know that RichTextBox does not use the Rich Text Format internally. It uses WPF’s FlowDocument internally for formatting. This is actually good because you will find easier to work with WPF text model then to work with native RTF. Now you might think then why is it called as RichTextBox, the reason is that Windows call anything that supports rich text as RichTextBox. Also it supports RTF because whenever you copy any rich text from the clipboard to the RichTextBox it will treat it as rich text and vice versa as well i.e. when you copy text from RIchTextBox to Clipboard the formatting is not lost.

Both TextBox and RichTextBox derive from the same BaseClass which is TextBoxBase and hence support some common clipboard operations like copy, cut, paste.

  • PasswordBox – This textbox does not share the same base class as the other two. This is designed for editing password and the reason why it does not use the same base calss is that it does not want to offer some clipboard operations like copy, cut as these cause security risks.

 

The TextBox and RichTextBox both support spell check functionality. All you need to do is to set the SpellCheck.IsEnabled equals True and you would get spell check in the textbox. When you type a wrongly spelled work into the textbox you would see a red underlined in the misspelled word and also when you would right click on the misspelled word it will give you options to correct the spelling.

 

Spell Check

Spell Check

When xaml comes across the dot in SpellCheck.IsEnabled it treats the IsEnabled property as an attached property (An attached property is one which defined by a different class than the target object). So here the property is being used by the Textbox but the Property is defined in the class SpellCheck. This might seem a little odd to you at first but if you think about it, it’s an excellent idea to add properties to existing classes without modifying them.

The way a xaml compiler interprets this attached property is as below.

 

Spell Check in C#

Spell Check in C#

So the SpellCheck class uses these access methods like get and set to access the attached property and that’s the exact same way the mobile .NET property really do.

Now most the times we have a label in front of our textboxes and we might want to focus to the textbox using a keypress. Now if use the following code then we could achieve what we intend to.

 

Focus Targetting

Focus Targetting

I would say the main job of the label is focus targeting. If you want to just display some text then I would recommend a TextBlock. That’s what a Label uses internally. If you just want to display some text not use focus handling then using a label will be overkill.

Range Controls

Slider, ProgressBar and ScrollBar share a common base class named RangeBase. These share common properties that they define values within a range. Slider and Scrollbar provide you an option to drag and change the selected value where as in PrgressBar we cannot do so.

 

Items Controls

There are many items in WPF that can display multiple items like: ListBox, ListView, TreeView, ComboBox and they derive from a common base class which is ItemsControl. This class provides the Items property to hold the child items and also common sets of events along with the databinding support. As you see in the image below that except the TreeView all the other Items Controls derive from class selector which provide the provide the property to handle a selected item but you can still select items in the treeview as well. Actually the selector should have been named as an IndexedSeletor as it provides the indexed selection property. And as the Indexed selection property only makes sense for linear lists hence so those are the classes which are derived from the selector class.

Items Control WPF

Items Control WPF

You will also notice that the ListView is derived from a ListBox and the only difference between a ListBox and ListView is that ListBox does not have support or Column Headers. All the Items Controls have a Content Model which is similar to Button that we have already seen before and supports any number of child items.

If you put the code shown in the image in a WPF app then you would be able to realize how flexible the Items Control are.

 

Items Control WPF

Items Control WPF

As any items Control is very flexible this negates the need of a DataGrid which is not present in WPF.

Some other Items Controls are Menu, Tab Controls (Derive from the Selector class) and Toolbar. So we can generate the content of these controls as well from data binding.

 

Items Control WPF

Items Control WPF

Items Controls and Content Models

So now we have seen many Content Controls and Items Controls. As could see in the table below there are four content model classes from which the different controls derive

 

  • The Button and Label derive from Content Control class that support only a single content property. This is also the base class for Window as Window supports only one content.
  • Headerd Content Control which derives from the Content Control and is inherited by Exapander, GroupBox and TabItem. So you have a have a header along with content.
  • Items Control which provides the Multi Content Model. Each item in the list gets its own instance of it content model.
  • Headered Items Control which derives from the ItemsControl but adds an header just like the Headered Content Control. So this is used by Items Contols that have  children and also use a header like TreViewItems, Menu Items.

It’s also possible add new Content Model.

Items Containers

The way the Items Control provide Content Model to its children is that each child gets wrapped in its own nested control. So for every item we add to a a ListBox the ListBox adds it to the ListBox ItemsControl. Similarly ListView Wraps its children into lisview items control and so on. So these wrappers are called as Items Container and each ItemsControl Define its own Items Container. We can also define custom ItemsContainers. So we add the following code to a WPF UserControl we could see header, container,etc

 

Items Control in WPF

Items Control in WPF

 

Events

There are 3 types of Events in WPF

  • Tunneling Events – These events start from the Root Element and move down the child elements towards the Target Element. These represent the Preview Events.
  • Bubbling Events – These events start from the Target Element and route up towards the Root element. These represent the main events
  • Direct Events – These events do not route at all but just directs towards the target element and that’s all. These used at place where tunneling or bubbling does not make sense like mouseEnter and is only raised for target element.

 

Lets see an example. Add the code shown below in a WPF application

 

Events in WPF

Events in WPF

 

Events in WPF

Events in WPF

As you would see we have used MouseEnter and MouseDown Events handler. When we write the code like above and add handler using += then the code and xaml and very tightly coupled. The code makes assumptions about the xaml but the xaml does not have any assumptions about the code. But we add method names into the xaml we have xaml also making assumptions and there methods and handler are treated as attributes. Also when you used Visual Studio or Blend they add function names in the xaml and hence we wish to rely on these design tool s then we should utilize the xaml attributes approach.

If have a look at the output widow while running the application you would see that the mouse enter events are direct events and the mouse down events are bubbling up.

If we remove the background for border and the stackpanel then the white area which you see is the window and the same will be reflected by the Mouse Enter and Mouse Down events. Also if you change the background to transparent for stackpanel and border we would have the same look as no background but will behave the way there is a background.

Now if want the bubbling to stop then we can add e.Handled = “true” to the event handler where we want it to stop bubbling further.

Let’s add some more code to the cs file.

 

Events in WPF

Events in WPF

So when you click on a button the background will turn green. But we have not used event bubbling. So lets change the code a little bit to use event bubbling, so lets add the handler to the stackpanel to handle the button click.

 

Events in WPF

Events in WPF

 

When we run this we will get an invalid cast exception, so we need to change the code again a little bit. The event is not originating from Button, its originating from the element to which we have attached the event handler to.

 

Events in WPF

Events in WPF

Commands

Commands are the actions that the user would like the application to perform. WPF defines a lot of builtin commands. We could see some of them below:

 

But need to note here that these commands do not actually do anything. These commands are nothing more than a name unless you define as what these do would. But the controls in WPF have defined these commands in their implementations. Like the textbox has defined the implementation of the copy, cut and paste command. The pattern for the command is that commands on their own do not mean anything but they need to execute in the context of a particular control. So lets implement a command handler. Put the following code in a WPF application.

 

Commands in WPF

Commands in WPF

When you will run this app you will see that both the buttons have greyed out. This is because these do not know what to do with these commands. So let’s provide a handler for these commands to work. So add the following code in the code behind and you would see the commands working.

 

Commands in WPF

Commands in WPF

You could also use CanExecute property to decide at the runtime as to whether that property is available to run or not.

We could also bind the commands with the Menus. So we add built in commands to menus then the menu will be able to figure the shortcut key for each command and show it. It is able to do that becase each builtin command knows what its shortcut key is.

 

Also we don’t have to say ApplicationCommands.Copy. Also we have not specified the command objects text and so the menu looks up the display text for the commands and shows that. So the commands display the local language display text. But the access key is not available for the Menu items so if we want the menu items to have access key we need to specify the header. The reason that it is not done automatically is that commands are at application scope whereas the access keys are menu item scope for example in File Menu P would mean Print but in Edit menu P would mean Paste.

Now when you run the app you would see that the commands are working without writing any code that is because TextBox has registered the command binding for these commands.

 

Commands in WPF

Commands in WPF

If we do not wish to use commands we could input gestures to provide the keyboards shortcuts for these items.

 

The code for this post can be downloaded here

Any questions, comments and feedback are most welcome.

 

Hey guys,

In this I am going to start talking about Windows Presentation Foundation or WPF in short. I hope you guys find this series interesting and informative.

So once you have decided to Learn WPF do not a step back or leave it in between because once learn the full power of WPF you would know how to create windows and web applications with awesome graphics easily.

What is WPF

At the very basic level WPF is just a framework which is used for building Windows application. Before WPF the windows applications majorly used couple of dlls (User32 and GDI32). These were the 32 bit versions of their 16 bit parents who were introduced in mid 1980s. Now if you have worked in Windows Forms you would know that the interface that you used to create an application were just a wrapper around these dlls.

Why to Use WPF

But WPF does not use GDI32 and barely uses USER 32. It’s not just a wrapper around these dlls. WPF was introduced as part of .NET 3.0 framework. It contains both managed and unmanaged code. It was designed from scratch so that .NET languages could be used to program in WPF. You would need to use .NET to use WPF as these are no public unmanaged API offered for this. This provides a lot of advantages as you don’t have to struggle with the issues you face using a wrapper around the unmanaged code. You need to be either on XP SP3, Vista, Windows 2003 or above to use WPF.

You might still be wondering as to what’s the thinking behind creating a new framework such as WPF when we already have a Windows Forms for creating a Windows application which is used by lot of people and huge numbers of people are skilled in it. The reason is Microsoft did not want to lag behind after all the thinking and market changes that have happened since the initial framework for creating windows application was launched and was really hard to keep the future versions compatible with it ancestors. As whenever an upgrade happens to a new version, people expect it to be really smooth. At the time when the initial Windows application development architecture was designed then the computer was not capable of so much processing power or graphical capabilities. Nowadays the computer hardware capabilities have progressed in leaps and bounds. So there was a need to design a framework that could utilize that capability. WPF provide the interface using which could design rich graphical user applications without having to deal with complexity of the directx or OpenGL code. Now the old dlls that were used in creating WPF application does not provide any way of utilizing the directx capability unless you are ready to program in directx or OpenGL.

WPF is also auto scalable by default which means that if you run you WPF application on machine with different DPIs you application will automatically scale its contents according to the DPI and resolution of the machine. You can simply see that in action by simply creating a WPF application and zooming into it. If you zoom into other applications or graphics in your system you see it getting pixelated but with WPF you will not see that.

As the times have changed, people’s expectations from the applications have changed. A decade ago people were okay with console application running on their computers but today they want a rich and cool user interface to work with. The games that we see now have reached that level and same can be achieved for windows application using WPF. You can make your complete application be blended into a single theme that you want, like your company logo colors, etc.

It was easy to make websites carry branding before using HTML as anyone without any programming experience can also use HTML to make a nice looking website which corresponds to your company. WPF also utilizes the power of Markup to give the designer the ability to do more and be part of the graphical interface easily. The use of markup makes the Windows apps move forward to the level of web apps styling easily.

Now in today’s time we do have the option to create a visually appealing application but the problem is to integrate all those component together that make that visually appealing application. We do have HTML for Web, Win32 with easy interface for Windows applications, DirectX or OpenGL for developing rich graphics application and Flash for designing rich vector graphics but all these have different capabilities and it’s really difficult to integrate all of them together. But WPF provides us with a single integrated solution for it. The capabilities that WPF provides are already available with the technologies I mentioned before but the advantage with WPF is that it provides all these capabilities at one place and integrated.

WPF Architecture

As you could see in the image below the basic architecture of WPF is designed with directx at its base above kernel.

 

WPF Architecture

WPF Architecture

WPF utilizes the 3D hardware your system to render 3D or 2D graphics on your system. On top of Directx level is the most basic component of WPF called as the Media Integration Layer or MIL. This is the component that takes the various types of media like the bitmaps, images, videos, etc and renders them all into a single directx surface. This MIL is unmanged code because it has to talk to directx and there need to be lot of calls need to be made to the com interface while dealing with directx and directx uses a lot com calls as they are cheap in its context but when you come to .Net code that is not the case. Using com from needs you to go through the interop layer and made thousands of call through the interop layer wil burn a lot of CPU cycle. So that’s the advantage to MIL, as to render a complex shape you make just one interop call to MIL and MIL then internally makes thousand and hundreds of com calls to DirectX to render that shape. Above the MIL we have two dlls for WPF. Presentation Core and Presentation framework. Presentation core is the public face of the MIL, it provides the .NET API that exposes he rendering services of the MIL. Above this presentation core we have the Presentation Framework layer that provides the high level services. Presentation layer provides the concept of Controls, layouts, data binding, animations, etc. As a WPF developer you would be spending most your time with Presentation framework. And you would be using the Presentation Core at the time graphics programming. The reason for separation of these layers is to make the rendering available without being dependent on WPF features.

What is XAML (Extensible Application Markup Language)

When you create a WPF application you would see two code files in your project. One is the regular .cs or .vb file which is your standard code file and the other one is you XAML file which is something new to WPF. Now a XAML file looks a lot like a XML file. Now if you would have created a WPF application in the past then you would have seen XAML. I would like clarify here that XAML is independent of WPF and WPF is independent of XAML. They are separable. XAML is nothing but a language to create .NET objects and this means we could what we do XAML in C# or VB code as well. It’s on you to decide what to use when. So if you see the image below you would find XAML and its corresponding C# code.

 

WPF XAML

WPF XAML

Now XAML uses the type converter infrastructure to map the string and integer values to map to the property values at the run time. And it also XAML in knows as to what does the content contain. The most simple and important thing about XAML is that it creates objects and sets properties. Also when you create a WPF application and open any of the XAML files you would see something like this at the top of it.

 

WPF XAML

WPF XAML

This is simply references to the namespaces so that you could use the components in that namespace. If you are referencing any namespaces in xaml then this is the place to add them. Microsoft took a long time in developing xaml and figuring out how xaml does what it actually does.

UI Tree in WPF

The XAML interface objects are built as trees of objects. As you would see in the code below,

 

UI Tree in WPF

UI Tree in WPF

Here we have root element which is a Window. This Window contains a single child which is Grid. The grid contains other children and it’s the Grid job to assign as to where these children are placed in the layout. So you see a tree root structure.

WPF provides two tree structures: The Logical Tree and The Visual Tree. The visual tree will be of use if you are concentrating on the presentation.  The Visual Tree is simply the super set of the logical tree. You can see below that all the children of the logical tree are present in the visual tree. So these two trees are the different views of the same set of the objects that make up the UI. The logical tree provides you with the detail to focus on the core structure of the User Interface and to ignore the details of how exactly it is presented.

 

Visual and Logical Tree in WPF

Visual and Logical Tree in WPF

 

Events and Commands in WPF

There are two ways for handling input in a WPF application: Events and Commands.

Events are very closely tied into the visual tree. Any Mouse or keyboard inputs originate from an element. The one with the focus – keyboard input and the one with the stylus – mouse inputs. As we have already seen that the visual tree was pretty complex for just a couple of elements, you could imagine the complexity if there are a lot of controls in your visual tree. It would become all the more complex if you add an event handler to every element of the visual tree to receive the inputs.

To save us from this complexity WPF has Event routing. Event routing allows the ancestor of the element to handle the event. Now there are two types of routing in WPF – Tunneling and Bubbling.

Tunneling starts from the root of the visual tree and goes through the tree and reaches the element to which the event is targeted. Generally Preview events are the ones that tunnels. Bubbling Event works in the opposite direction. It starts from the Element and goes up the parent to the root. Main events are the one that bubbles. The concept behind providing a preview is to give the parent element a chance to handle the originating event.

For example if you have a button in the Grid and you want to handle the Mouse down event. Now if you want Grid to handle the event before the Button does you need to use the Preview events (PreviewMouseDown) and if you want the button to handle the event first then you should use the main event (MouseDown).

Commands on the other hands help you do the same action through multiple inputs like a keyboard shortcut, stylus gesture, menu clicks, button clicks, etc. So that multiple inputs can use the same command if they want same job to be accomplished.

Controls

Controls in the previous versions like Windows forms correspond to behavior as well and presentation of an element, whereas in WPF controls are a bit different. Let’s take a Button for Example, a button has a click event which is an API feature related to the user interaction. It also supports the content Model for composition which is also an API feature. It supports Focus which is an interactivity feature. It can be associated with Command which is again an API feature. It also supports the Automation API which makes it accessible to screen reader, automation testing, etc. But there one thing that a WPF button cannot do which its activex, Win32 counterparts can.

A WPF button is a lookless control which means it has no intrinsic look and it does not know how to present itself. The look of a control in WPF is controlled a distinct entity known as Template. So button may look like a circle or a star but it will still support all the API and interaction features. Let see how this works in code.

Use the following code in a WPF application and you would be able set the template property for the button control.

 

Controls WPF

Controls WPF

 

You should notice a few things about the code above.

  • We have defined a ControlTemplate for the Button which changes the look and feel of the Button.
  • The Fill property of the Rectangle in the ControlTempalate is done using the TemplateBinding with Background. What this does is binds the Fill of the rectangle to the Background of the Button. So whatever background we set on the Button becomes the Fill of the rectangle.
  • You would also see Curly braces around the TemplateBinding which signifies that it a special property. This is considered to be Markup extension. Markup extension signifies that it would be decided at runtime as how this property will work. This syntax means that we need to create an instance of the TemplateBinding Class with Background as a string and a constructor parameter and WPF expects the whole thing inside the curly braces to derive from Markup extension base class. Now this Base class provides an abstract method named Provide Value. This method would be called at runtime to decide what value will the Fill property have a runtime. A custom markup extension can build depending on what we need.
  • You would also see the same thing as Rectangle Fill Property for TextBlock Text Property.

Lets change the code to look something like below:

 

Controls WPF

Controls WPF

You would now notice that the Content of the Button is now and Ellipse and to make that as the content of the button we need to need to use a ContentPresenter instead of a TextBlock because a TextBlock is a primitive control and it could only display text. So to display the any content we need to use the ContentPresenter and TemplateBind the Content property. So if we want any other content we could do that now.

Primitive Elements in WPF

As you have seen that the controls do not define their own look, so are you not wondering as to how do anything appear. Just as we saw above a button control derives its look from its template, and the controls derive their appearance from there templates so is there an infinite loop to look for the template?

That’s not the case. Only the controls have a template and most elements in WPF are not controls. Only the Controls that derive from the Controls Base class are supposed to have some kind of interactive behavior. Examples of controls are Button, TreeView, ListBox, TextBox, etc. Only the Controls derived from the Controls class have a template because it’s the Control class that introduces the template property.

Examples of Elements are Rectangle, Ellipse, Image, TextBlock etc. These do not derive from Controls and are more primitive and derived from FramworkElement (Base class for Controls as well). These elements do not have a template of their own and as they are more primitive and there presentation is specifically designed. Primitive elements are the one that provide an intrinsic appearance for them. These can be also considered to be lookful controls. Primitive elements do not have any intrinsic behavior of their own and you have to add the events and handler to get some interactive behavior from them.

You might note that a lot of elements that do not derive from the Control Class are placed in the namespace System.Windows.Control. This is confusing you should keep in mind that the Elements that derive from the Control Class are Controls.

Layout in WPF

The new and useful feature in WPF is the Layout primitive also known as Panels in have. The Panles are required at places where we need to position multiple childrens. The panels available in WPF are Grid (Advanced table/grid-based layout), Canvas (Fixed layout, supports anchoring), StackPanel (left to right and top to bottom layout), DockPanel (Docking layout) and WrapPanel (Flow-like formatting).

Flowed Text in WPF

WPF provides a flow layout for the text so that the text fits into whatever space is available. A Flow document has a HTML-like feature set and it has reader controls.

In a flow document we can integrate any mixture of text styles, user interface elements, HTML features (Lists, floating data, etc). WPF makes it much easier to render text in columns than HTML which is very useful because columns allow shorter line lengths which improves reading speed.

Data Binding in WPF

When you come across data binding you would think about databases or collections but in WPF databinding has much broader scope. Data Binding can be used at times when you want to present any data to the screen. WPF data binding either connects to objects or xml. WPF never assumes the presence of a database. Infact you never use data binding directly with database. You load the data from the database into your domain objects, datasets, etc and then data binding presents them on screen.

Data Binding brings up a very interesting concept in WP Known as DataTemplate. Similar to ControlTempalate which defines how a control should look like, DataTemplate defines how the data should look like. So you define the template for a particular class of application and the template can be used to present the data on the screen.

Its because of the power of Data Template that WPF does not contain a DataGrid as you could define how the data should be presented on screen.

Deployment

There are multiple ways in WPF to deploy the application to the user machine:

  • Build a MSI installer
  • Click Once deployment but is supported only in full trust environment.
  • XBAP – XAML Browser application. This is like the Click once but imparts the experience like the java applet style. This does not require full trust as it runs in browser.
  • .NET 3.5 SP1 deployment options
    • Client only framework – option to deploy only a part of the framework. Can be deployed in following ways:
      • Setup bootstrapper – this installs the framework before going to the normal windows setup
      • Deploy via Click Once

The code for this post can be downloaded here.

Any questions, Comments and feedback are most welcome.

Hey guys. Today i am going to discuss about the MediaElement in Silverlight and see how we can put it in use in Silverlight and WPF applications. We can integrate media into our Silverlight pages and WPF UserControls.

 

MediaElement Objects

To add media to the Silverlight page just add a MediaElement to your XAML and provide a URI (Uniform Resource Identifier) to the media to play. The code below will show you how to create a MediaElement and set its Source proprty to URI of a video file. You can add the video file to Visual Studio project also and then set its property to Resource and the MediaElement will begin playing when the page loads.

XAML

<StackPanel Width="300" Height="300">
  <MediaElement x:Name="media" Source="xbox.wmv" Width="300" Height="300" />
</StackPanel>

Note – The MediaElement object can play WMV (Windows Media Video), WMA (Windows Media Audio), MP3 Files.
MediaElement Properties
The MediaElement object provides several media-specific properties. The following list describes the commonly used properties.

  • AutoPlay: Specifies whether the MediaElement should begin playing automatically. The default value is True.
  • IsMuted: Specifies whether the MediaElement is silenced. A value of True mutes the MediaElement. The default value is False.
  • Stretch: Specifies how video is stretched to fill the MediaElement object. Possible values are None, Uniform, UniformToFill, and Fill. The default is Fill.
  • Volume: Specifies the volume of the MediaElement object’s audio as a value from 0 to 1, with 1 being the loudest. The default value is 0.5.

In addition to its media-specific properties, MediaElement also has all the properties of a UIElement, such as Opacity and Clip.

Controlling Media Playback

You can control media playback by using the Play, Pause, and Stop methods of a MediaElement object.

XAML

<Grid>
   <Grid.ColumnDefinitions>
         <ColumnDefinition Width="*" />
         <ColumnDefinition Width="*" />
         <ColumnDefinition Width="*"/>
     </Grid.ColumnDefinitions>
     <Grid.RowDefinitions>
         <RowDefinition Height="*" />
         <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <MediaElement x:Name="media" Source="xbox.wmv" Width="300" Height="300" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3" />
    <!-- Stops media playback.-->
     <Button Click="StopMedia" Grid.Column="0" Grid.Row="1" Content="Stop" />
    <!-- Pauses media playback. -->
     <Button Click="PauseMedia" Grid.Column="1" Grid.Row="1" Content="Pause" />
    <!-- Begins media playback. --> 
    <Button Click="PlayMedia" Grid.Column="2" Grid.Row="1" Content="Play" />
</Grid>

 

C#

private void StopMedia(object sender, RoutedEventArgs e)
{
     media.Stop();
}
private void PauseMedia(object sender, RoutedEventArgs e)
{
    media.Pause();
}
private void PlayMedia(object sender, RoutedEventArgs e)
{
    media.Play();
}

Visual Basic

Private Sub StopMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Stop() End Sub
Private Sub PauseMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Pause() End Sub
Private Sub PlayMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Play() End Sub

Video Player Sample with Code

The following example illustrates typical features of a video player including playback control, a progress/seek slider, and full screen toggling.

Smooth Streaming

Smooth Streaming is an IIS (Internet Information Services) technology that enables adaptive streaming over HTTP to Silverlight clients.  Smooth Streaming breaks video feeds into small fragments which enables it to quickly alter the quality of the video, depending on the current bandwidth of the client.  This creates a high-quality viewing experience that scales massively on content distribution networks.   For more information on Smooth Streaming, see the IIS Smoothing Streaming site.

For an indepth example of Smooth Streaming, see the Microsoft Silverlight Media Framework CodePlex project.