File Access Option

In Silverlight there are 3 main ways of accessing files:

  • OpenFileDialog and SaveFileDialog – This is the most flexible of all the file access options as this can be used by any Silverlight application running at any permission level. The user can select any file as long as the user has permissions for the same. The user will have to select the file to read and while saving the user has to specify the filename to override or save as. The code has no permission to know the location of the file and unless the code has elevated permissions the path of the file cannot be known rather only the filename is available. The ability to know the exact path or location is considered to be a security risk by Silverlight. Also these File dialogs are also not allowed until the code for these dialogs is being run in an event handler for user input.
  • FileStream, StreamWriter – The second way is to use the different classes in the System.IO namespace. Silverlight offers classes like File, FileInfo, Directory, DirectoryInfo, FileStream, StreamWriter, etc. In these operations user is not involved. This mode of operation is available only for the trusted application. Not all Silverlight applications can use unless the application is running under elevated privileges.
  • Isolated Storage – A Silverlight application can read or write files to the Isolated Storage without needing the user to be involved. The files can be read or written. The only catch is that the files are saved in the private storage which is under the user directory and the path is not available. So you can just use it as a private store of files where you can access the files. There is no access available for the user files and neither the user can look at the files that are saved unless the user looks into the most of the hidden folder and files under their directory. So the main purpose of Isolated Storage is to provide the application the fast and easy access of files store without user input or elevated trust. But this storage is not reliable as the user can always delete the files.

Let’s have a look at each of these File Access methods in detail:

SaveFileDialog

The SaveFileDialog uses the same file save dialog box supplied by the operating system. To use it we need to create an instance of the SaveFileDialog and call the ShowDialog method. It returns true or false depending on whether the user selected a file or not. The return type of ShowDialog method is nullable bool so we need to compare the return value of the ShowDialog method with true to proceed further with the file selected. However the ShowDialog never returns null but this is the way it is designed. As you can see in the image below once we verify that the user has a selected a filename we can open the file. We can get the filename of the file from the SaveFileName property but the path is not available. So the only way write data is to write the string returned by the dialog.

 

Silverlight 4 : Save File Dialog

Silverlight 4 : Save File Dialog

From the perspective of .Net this is only a string which we can put in a StremWriter to write text into it. If we want to write binary data into it then we can use the Stream Object directly. We can browse to the selected folder and have a look at the saved file.

OpenFileDialog

The OpenFileDialog is similar to the SaveFileDialog. The major difference being  that FileOpenDialog offers a property called multi select which when set to true the user can choose multiple files. So the OpenFileDialog being more complex does not offer a OpenFile method. So depending on whether the OpenFileDialog is in single file or multi file mode we need to use the File or Files property respectively. So as we see in the image below we call File.OpenRead as we are dealing with single file. In the multi select mode we would use the Files property which would return a collection of FileInfo object.

 

Silverlight 4 : Open File Dialog

Silverlight 4 : Open File Dialog

FileStream

The usage of FileStream is quite similar to the regular .NET File access using FileStream. However in Silverlight only application running in elevated trust are allowed to use this technique which is available only in Out of Browser mode. Another restriction in Silverlight is that the files only in specific folder location are available using FileStream. The accessible files are the ones which are in the Users Documents, Music, Pictures and Videos. The reason is because Silverlight runs on multiple platforms and the file system on these platforms might be different and location of these folders might be different on different platforms. We need to use the Enviorment.GetFolderPath method to access these folders. We can also inspect the directory structure beneath these folders using the Directory and DirectoryInfo class in System.IO.

Isolated Storage

It provides storage associated with the logged in user. The API presents data from the stream class from the System.IO namespace. This storage can be used to store either text or binary data. It’s called as Isolated as the storage is partitioned and the Silverlight application have access only to specific parts. Firstly, the storage is partitioned as per the user so that the apps do not have access to the storage space allocated to the other user of the machine. Secondly, the storage is partitioned as per the site and optionally as per the application in the site as well. The partition of the isolated storage depends on the xap files that the apps access. The isolated storage is not dependent on the hosting page. If the multiple pages of an application access the same xap then they will share the same isolated storage. This works for a multi-site website as well. So if multiple sites download the same xap file then the Silverlight supplication will have access to the same Silverlight application isolated store. The Silverlight application provides 1MB of space by default for each user. If the application has more space requirement then it can ask the user for it. Isolated storage is available across browsers on the same machine similar to sharing the cookies across all bowsers, it takes the cross platform support to whole new level.

 

You might be surprised to know that Silverlight is not the pioneer of isolated storage. It was introduced in Widows forms to store data from the web in the partial trust scenarios. Although the method of access is different and there is no way to access the full .Net framework featured Isolated storage.

Now let’s see how to Write to the Isolated storage. Add the following to your Silverlight application.

try

{

//Obtaining the isolated storage from the user

using (IsolatedStorageFile isoStore =

IsolatedStorageFile.GetUserStoreForApplication())

{

//Create new file

using (IsolatedStorageFileStream isoStream =

new IsolatedStorageFileStream(“MyData.txt”,

FileMode.Create, isoStore))

{

//write some content to the file

using (StreamWriter writer = new StreamWriter(isoStream))

{

//Writing line to the file

writer.WriteLine(“Isolated storage is a cool feature”);

}

}

}

}

catch { }

 

As you would see that we need to begin by asking the user specific store for the application. We can also get the user store shared by all the application on the site by calling GetUSerStoreForSite(). The method returns the directory. Then we create an IsolatedStorageFileStream and the constructor requires the IsolatedStorgaeFile as one of the inputs. So here we create a new file in the store but we do not know the location of it. Then we wrap the IsolatedStorageFileStream into a StreamWriter and we write to that file.

Reading from the Isolated storage is very similar with 3 changes. FileMode.Open instaed of FileMode.Create, StreamReader instead on StreamWriter and reader.ReadLine instead of writer.WriteLine.

 

try

{

//Obtaining the isolated storage from the user

using (IsolatedStorageFile isoStore =

IsolatedStorageFile.GetUserStoreForApplication())

{

//Create new file

using (IsolatedStorageFileStream isoStream =

new IsolatedStorageFileStream(“MyData.txt”,

FileMode.Open, isoStore))

{

//write some content to the file

using (StreamReader reader = new StreamReader(isoStream))

{

//Writing line to the file

String sb = reader.ReadLine();

_isolatedStorageReadText.Text = “Read from UserData.txt: ” + sb;

}

}

}

}

catch { }

 

Deleting from the Isolated Storage. To delete the file from the Isolated we do not need to wait on the user. We can use the code below to do that.

try

{

//obtain the Isolated Storage for the user

using (IsolatedStorageFile isoStore =

IsolatedStorageFile.GetUserStoreForApplication())

{

//Delete

isoStore.DeleteFile(“UserData.txt”);

}

}

catch { }

 

Increase the Quota for the Isolated Storage

There is an option for the application to ask for more Isolated Storage space from the user but its not necessary that this space will be provided as its up the user to provide that space. The additional space request should be made at some user input because if its made at any other time then Silverlight will automatically fail the request. This means the extra Quota is only available to the applications with which the user is interacting. The following code can be use to request for additional isolated storage space.

using (var store = IsolatedStorageFile.GetUserStoreForApplication())

{

Int64 spaceToAdd = 5242880;

Int64 curAvail = store.AvailableFreeSpace;

if (curAvail < spaceToAdd)

{

if (!store.IncreaseQuotaTo(store.Quota + spaceToAdd))

MessageBox.Show(“Increase rejected.”);

else

MessageBox.Show(“Increase approved”);

}

else

MessageBox.Show(curAvail.ToString() + “bytes is available”);

}

 

Silverlight 4 : Increase Quota Isolated Storage

Silverlight 4 : Increase Quota Isolated Storage

The users not have the option to wind the quota back as Silverlight does not know which file to trim to remove the quota.

You can download the source code for this file here.

 

Any comments, feedback and questions are most welcome.

 

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.

 

 

Guys,

In this post i am going to talk about about the F# application structure.

  • If you have worked with any programming languge then i would expect you to know that modules are the building blocks of an application which form the structure of an application. These are the container that contain the F# functions, types and values. We could also think of a module as a static clas in C#
  • If F# we could have multiple modules in the same code file but one module could not span multiple code files.
  • A module lives in the .Net namespace hierachy. This could be controlled by the programmer as to where does the module resides in the .Net namespace hierarchy. If we are writing a simple F# program we might not see modules being cretaed as that is taken care by the F# comipler internally. Also as you would expect from F# having really good inference capbility, it automatically recognizes the entry function (main function) and structures it.
  • If we have multiple possible entry points in the F# application then we need to use the [<EntryPoint>] attribute to define the entry point of the program manually do that the F# compiler recognozes where to start.
  • Let see this action. Add the following code to an F# application and run it. We ould see something like the below screen:

 

Run F# Function

Run F# Function

  •  Now lets add a new module in this application. Right click on the project name and select add new item and add a new F# sourcefile and name it Calcy.fs
Add New Item F#

Add New Item F#

 

Add New F# Source File

Add New F# Source File

  •  Once you hit ok, you would see that the new file is cretaed and the it starts with Module Calcy. Lets do one thing lets cut the first 2 lines of code from our program.fs and paste it below module Calcy in Calcy.fs
F# Module

F# Module

  •  Now in Program.fs we we would see that the compiler is complaining. So what we need to do is prefix the intAdd function with our module name like below:
Call Function from another module

Call Function from another module

  •  But you can see that the error still persists. Wonder why? Its because F# evaluates functions as well as files in the order they appear. So as the Calcy.fs is present below the program.fs in solution explorer we cannot use the functions present in Calcy module. So just right click the Calcy.fs file and click on move up and you see the error disappear from your Program.fs file. We could run the application and see that it works absolutly fine.
Move File Up F#

Move File Up F#

  • The F# compiler would still automatically create a module from the program.fs file but if want you refer it from a from program in other .Net language then we should know the name of the module and hence it is a good idea to give the module in Prorogram.fs a name. So change the code in Program.fs as below:
F# EntryPoint

F# EntryPoint

  •  Now here we have multiple things to note. We have specified the module name. We have specified that this main function is the entry point to our application. Also you would see that i have specified a return value of 0 for the main function. This return value is required as the main method expects a return value of type int.
  • Now lets modify the Calcy.fs and make it contain 2 modules. You would still see that there is an error which expects us to specify a namspace so that distintion can be made between the modules.
Multiple Modules in 1 File F#

Multiple Modules in 1 File F#

  •  Lets add the namspace as global and change the code accordingly in Program.fs as the module names have changed and run the app and it should work fine.
namespace global F#

namespace global F#

 

Run F# App

Run F# App

  •  Now if we want to use any other custom namespace other than the global namespace then we need to open that namespace before we can use it otherwise the F# complier will complain. In F# we could also just opn the module instead of the whole namespace and this is an extention the using keyword in the C# language. This gives use the flexibility to remove the module name suffix before the intAdd funstion in Program.fs
Custom Namespace F#

Custom Namespace F#

  •  If we modify Program.fs module to be part of the same namespace as Calcy.fs modules we do not need to open the namespace which makes perfect sence.

You can find the source code for this post here

 

Any questions, comments an feedback are welcome.