ePlaice / For the Best Software on the Net

Mainly Free and Open Source Software


WPF Navigation

SVG to XAML Conversion | Standalone WPF Applications | Silverlight 3 | Project Template for Silverlight 3 | Silverlight Libraries | XAML Introduction | WPF Data Binding | WPF Styles and Templates |

Valid XHTML 1.1

Latest news

10 Jul 2009: Silverlight Version 3 released

22 Aug 2008: SharpDevelop 3.0 Beta 2 has been released - you can get it on Sourceforge as well as at Sharpdevelop downloads.

Links:

XAML Introduction

I decided it was necessary to try to understand the basics of XAML before using any tools to generate the XAML code. I was motivated to learn enough so that I could at the least design a form in XAML which resembled say a data input Windows Form.

I noticed there was a fair degree of similarity between XAML and the HTML CSS specification which allows you to define styles which can then be used to provide a common look and feel for your Form. Obviously it's impossible to detail all the features of XAML in one web page so I have just concentrated on a few of what I consider to be the most important features. Also, as I have been using SharpDevelop 2.2 for building all my NET 2.0 examples, I decided to see how far I could get with WPF using SharpDevelop 3.0 Alpha. So far this has been a good learning exercise; the bits I am really waiting for are the WPF Designer and the Database Designer, but in the meantime it is still possible to build WPF applications.

Code versus XAML

As I went through I learnt was that pretty well everything that could be designed using XAML could also be achieved using code. From what I have seen so far the XAML markup looks very difficult to maintain (just as HTML) and debugging must be a nightmare, but perhaps with good design tools the amount of time actually writing or modifying the XAML code will be minimised. I am waiting for SharpDevelop 3.0 to allow you to drag and drop elements such as Grids and Buttons onto the Design View, with the ability to use the property editors to set properties such as border thickness, and background color, and events such as button click. With good tools available the choice of when to use XAML versus code should be no different to that currently found using the NET 2.0 Windows Forms elements. Ideally, the need to directly edit XAML code should be no greater than that required to edit the .designer.cs code in NET 2.0 - OK on the rare occasion I have jumped in and made a few changes but this is not recommended. However, all of this may be more difficult than appears at first sight when starting to consider the impact of styles, resources and templates across a number of controls. Where do these get defined in a semi automated way and how do the various controls reference these styles?

XAML Directions

Also as I go through I have to admit to being a little confused as to where XAML is going; it seems fairly clear that the NET 2.0 Windows Forms are out, to be replaced by WPF XAML forms. Does this mean that all the NET 2.0 applications based on Windows Forms will need to be converted to WPF? However, it is also clear that some of the elements in NET 2.0 are needed such as DataGridView to name just one. However, there are overlaps such as labels and TextBlocks - can these be used interchangeably? should we be using one set of elements for one application and a different set for another application or can we mix and match? OK, I am beginning to understand that you can call up a Windows Form DataGridView from within the C# code and then reference this to a XAML grid name using FindName - I just saw an example. So maybe it's not so bad after all.

Using Kaxaml

When you are playing around with XAML it is very useful to be able to see the results of your work using a simple to use editing and viewing tool, which is where Kaxaml fits in. I have been using this since version 0.2 and now with the version 1.0 release it has now become a really friendly and useful tool to have, particularly during a learning phase where one is still unsure just how code elements, styles and resources fit together. So now whenever I am putting together some XAML code I always give it the once over with Kaxaml.

Using SharpDevelop 3.0

The WPF Designer is beginning to take shape and it seems with the latest Build Server version 2917 it is already possible to build some fairly simple screens. Like Kaxaml it places the Grid element by default on the form and from here I have added some TextBoxes and Buttons using drag and drop. It is also possible to change the property values and also set up an event such as a button click. This all looks really promising for the future, so my next step is to set up some fairly simple forms and see how it develops. Some existing WPF applications will compile in SharpDevelop 3.0, but the designer does not display the windows currently, which is what you would expect from an alpha version. However, I remain most impressed by what I have seen so far and sincerely hope it will give the Microsoft tools some good competition.

Root Elements

In order to be classed as a well formed XAML file there can only be one root element defined, that will either be :-
Page - Represents a page of information that can be hosted on the internet
or
Window - Used to manage Windows and dialog boxes

Layout Panels

A Form can hold only one child object, in its Content property. You could add a normal control there, but then you cannot add any other control on your form. That is why the Forms Content object should be a control Container, that is a control that can hold other controls. Containers designed and shipped in WPF for this purpose are:-
StackPanel - For laying out Child elements one after the other in the order that they appear in the XAML code.
WrapPanel - The wrap panel lays out items from left to right. When a row of items has filled the horizontal space available to them the panel wraps the next item around onto the next line (in a similar way to how text is laid out).
DockPanel - The DockPanel allows elements to be docked to the edges of the panel's container, similar to Windows Forms docking. Items are docked in the order they appear in the XAML file (document order). The last Border element fills all the remaining space since no DockPanel.Dock attribute is specified for it.
Canvas - The Canvas panel allows you to control the absolute position of things by setting a Top and Left property for them. Additionally, instead of setting the Left to position an item you can instead set the Right, or instead of setting the Top you can set the Bottom. If you specify a Left and a Right the Right value is ignored, the element does not change its size to make both these values correct, and similarly Top takes precedence over Bottom. Elements that are declared earlier in the XAML file can appear behind elements that are declared later (if their positions over-lap).
Grid - The Grid panel is an extremely flexible panel, and can be used to achieve almost everything that can be done with the other panel controls (although often not with the same ease). The grid panel allows you to define rows and columns in the grid using XAML, and then place controls in calls in the grid using grid-specific attributes. Elements can span multiple rows or columns. The grid will automatically make all its rows and columns the same size (based on the size of the content) but you can specify a proportional size for rows and columns using a star notation, or specify an absolute width or height.
Border - Wraps its child control in a border.
InkCanvas - This is a control that uses Ink as its primary input, so you can freehand draw on the canvas.

Buttons

As for WinForms there are the usual buttons :-
Button - Similar to WinForms but with greater scope for decoration
RadioButton - Similar to WinForms but with greater scope for decoration

Other Controls

I just list some of the other controls that are commonly required in applications :-
TabControl - You can do all the work in XAML, without going near C#, to produce nice looking TabControls which can be made to look very similar to those in NET 2.0. I found a good article that explained how to get the best out of the TabControl at WPF Tab Control - Inside and Out - WPF Styles and ControlTemplates.

Boxes

Again the functionality is similar to WinForms with several additions:-
CheckBox - Similar control in WinForms
ComboBox - Similar control in WinForms
TextBox - Similar control in WinForms
GroupBox - Similar control in WinForms
ListBox - Similar control in WinForms
PasswordBox - A new control designed for entering and handling passwords
RichTextBox - Similar control in WinForms
ViewBox - A Viewbox allows the content of a single child object to stretch and scale to fill the available space of the hosting container of the XAML content. Typically the ViewBox would represent an area which is part of an original image.
ViewPort - Viewport represents the target area in our application where the area that is selected by Viewbox will be shown. Using Viewport you can manage the view of this area.

Views

I have just grouped the following view elements :-
ListView - This control is derived from ListBox and typically is bound to a data collection where it can be used to show a list of data items. Similar control in WinForms
TreeView - This can be used to show data items in a hierarchical view. Similar control in WinForms.

Bars

I grouped the bars together :-
ProgressBar - I found a good example of how to use this at The Look and Feel of a ProgressBar. I like this because it has a Vista style progressbar as well as several other types.
ToolBar - The XAML ToolBar is quite easy to use; see example below.

MenuBar

It is a very common requirement for an application to use a MenuBar and with NET 2.0 it is so easy to create the MenuItems you need with minimal effort. However, when I look at WPF it does seem rather complicated just to produce a fairly simple MenuBar. The following example shows how to apply a simple style when 'mouseisover'the MenuItem. It does seem a bit painful to have to apply this style to every MenuItem; there must be a better way! Also I tried without using a style and it took me some time to work out Foreground and Background colours that did not make the MenuItem disappear. Sorry but I'm not impressed - it would be useful if Microsoft released full code which simulated the NET 2.0 MenuBar with it's easy to attach icons and transparent overlay as you go through the MenuItems.

XML
<Window.Resources>
    <Style x:Key="Triggers" TargetType="{x:Type MenuItem}">
  <Style.Triggers>
    <Trigger Property="MenuItem.IsMouseOver" Value="true">
      <Setter Property = "Foreground" Value="Red"/>
      <Setter Property = "Opacity" Value="0.9"/>    
       <Setter Property = "FontSize" Value="11"/>
      <Setter Property = "FontStyle" Value="Italic"/>
    </Trigger>
  </Style.Triggers>
    </Style>

  </Window.Resources>
    <Menu
            VerticalAlignment="Top"
            HorizontalAlignment="Left"
            Height="20"
            Width="50"
            Background="AliceBlue">
            
            <MenuItem
                Header="File"
                StaysOpenOnClick="False">
                <!--For Creating Menu Item-->
                <MenuItem
                    Header="Input Data"
                    Background="AliceBlue"
                    Style="{StaticResource Triggers}">
                    <!--From here we are creating Sub Menu-->
                    <MenuItem
                        Header="Text"
                       Background="AliceBlue"
                       Style="{StaticResource Triggers}">
                    </MenuItem>
                    <MenuItem
                        Header="XML"
                       Background="AliceBlue"
                       Style="{StaticResource Triggers}">
                    </MenuItem>
                </MenuItem>
                <Separator />
                <MenuItem
                    Header="Save To File"
                   Background="AliceBlue"
                    Style="{StaticResource Triggers}"/>
                <MenuItem
                    Header="Load From File"
                   Background="AliceBlue"
                    Style="{StaticResource Triggers}">
                </MenuItem>
                    <Separator/>
                <MenuItem
                    Header="Exit"
                   Background="AliceBlue"
                    Style="{StaticResource Triggers}"/>
            </MenuItem>
        </Menu> 

ToolBar

I decided to look at the example of a Toolbar within a StackPanel container which makes use of Buttons and Images. I had a little bit of trouble getting the image to display in the .exe file, even though the images were showing perfectly OK in the SharpDevelop Designer. Eventually, I realised that the .bmp resource files had to be defined as 'Build Action - Resource' and 'Copy to Output Directory - Never'. Also it seemed to be a requirement to hold the bitmap files in a folder called 'Resources'. It was quite easy to add adjacent text to the images by just adding the text within the textBlock but after the image if you want the text to appear on the RHS. However, for some reason I could not vertically centre the text for some reason. Maybe I will experiment by applying some styles to see if the end result can be made to look better, but for the moment it seems it can be made to be nearly as good as the NET 2.0 default ToolBar.

XML
<StackPanel>
		<ToolBarTray
			Background="LightBlue">
			<ToolBar
				ClipToBounds="False"
				Focusable="False"
				HorizontalContentAlignment="Left"
				HorizontalAlignment="Stretch"
				Band="1"
				BandIndex="1">
				<Button
					Name="btnOpen">
					<TextBlock
						HorizontalAlignment="Center"
						TextAlignment="Center"
						VerticalAlignment="Top">
						<Image
							Source="Resources/open.bmp"
							Width="16"
							Height="16" />
					    Open
					</TextBlock>
				</Button>
				<Button>
					<TextBlock>
						<Image
							Source="Resources/save.bmp"
							Width="16"
							Height="16" />
					    Save
					</TextBlock>
				</Button>
				<Button>
					<TextBlock>
						<Image
							Source="Resources/paste.bmp"
							Width="16"
							Height="16"
							OverridesDefaultStyle="False" />
					   Paste
					</TextBlock>
				</Button>
			</ToolBar>
		</ToolBarTray>
	</StackPanel>