Saturday, June 7, 2014

Localization and Satellite Assemblies in WPF: How to support Localization in your WPF application?

Localization and Satellite Assemblies in WPF: How to support Localization in your WPF application?

In WPF applications, the unit of localization is the XAML file (technically, the compiled BAML resource that is embedded in your application). If you want to support three languages, you need to include three BAML resources. Satellite assemblies play an important role in localization of WPF applications. When you create a localized WPF application, you place each localized BAML resource in a separate satellite assembly.

To add localization support to your WPF application, just go to your .csproj file and add <UICulture>en-US</UICulture> under <PropertyGroup> element. Now Build your project and you will get a folder named en-US created where your exe is placed. 

If you go inside this folder, you will get an assembly with the same name as that of your exe but with different extensions. For example, if your application exe name is MySampleApplication.exe, its name would be MySampleApplication.resources.dll. This is called satellite assembly.

Now if you closely examine the size of your exe, it would be reduced because the BAML file is not embedded to it, but it is now contained in the satellite assembly which you just created.

When you run this application, the CLR automatically looks for satellite assemblies in the correct directory based on the computer's regional settings and loads the correct loacalized resource.

For example, if you are running in the fr-FR culture, the CLR will look for an fr-FR subdirectory and use the satellite assemblies it finds there.

Note: Extension for satellite assembly is .resources.dll.

How to localize your WPF application?

Step 1 (msbuild and Uid)

Add UID attribute to all the elements in your WPF application, you want to localize. You can use MSBUILD for adding the UID attribute to all elements used in your all the XAML files througout the application.

msbuild /t:updateuid MySampleApplication.csproj

Step 2 (LocBaml)

To extract the localizable content of all your elements, you need to use the LocBaml command-line tool. To extract the localizable details, you point LocBaml to your satellite assembly and use the /parse paramenter as shown here:

lcobaml /parse en-US\MySampleApplication.resources.dll

A .csv file will be generated named MySampleApplication.resources.csv

Step 3 (Build Satellite Assembly for other cultures e.g. fr-FR)

Again use locbaml tool with /generate parameter to create a satellite assembly with culture fr-FR.

locbaml /generate en-US\MySampleApplication.resources.dll
               /trans:MySampleApplication.resources.French.csv
       /cul:fr-FR /out:fr-FR

Friday, June 6, 2014

WPF Elements and Controls: Basic Concepts and Questions

WPF Elements and Controls: Basic Concepts and Questions

In this article, I have covered very basic concepts of WPF Elements and Controls in the form of questions and answers like the difference between elements, controls, content controls, headered content controls and layout containers, difference between tooltip and popup, difference between radiobutton and checkboxes, lexicon file etc. Last question illustrates the difference between resource files and content files in WPF (this question is out of the blog post title as these files are not WPF elements).

1. What is the difference between WPF Elements and WPF Controls?

There is a difference between WPF Elements and WPF Controls. All the WPF Controls are WPF Elements but vice-versa is not true. Any WPF element which can receive focus and accepts inputs from keyboard or mouse is called WPF Control.

For example: Textbox, Button are WPF Controls.

Exceptions: Tooltip and Label are also considered as WPF Controls because Tooltip appears and disappears depending on user's mouse movement. Similarly, Labels support mnemonics (shortcut keys), that's why Labels are also considered as WPF Controls.

Note: All the WPF Controls are derived from System.Windows.Control class.

2. What is the difference between WPF Controls and WPF Content Controls?

A WPF Content Control is the Control that can hold and display a piece of content.

For example: Button, RadioButton, CheckBox, Label, Tooltip, ScrollViewer, UserControl, Window etc.

Note: All the WPF Content Controls are derived from System.Windows.ContentControl Class.

3. What is the different between WPF Content Controls and Headered Content Controls?

Headered Content Controls are the Content Controls which have both content region and header region which can be used to display some sore of title.

For example: GroupBox, TabItem and Expander

Note: All the WPF Headered Content Controls are derived from HeaderedContentControl class.

4. What is the difference between WPF Content Controls and WPF Layout Containers?

WPF Content Controls can contain only a single nested element while layout containers can contain as many nested elements. You can also take a lot of elements in Content Controls but the condition is that all the elements should be wrapped in a single parent layout container like stackpanel or grid.

5. What is the difference between Label and Textblock in WPF?

Label and Textblock are used to display the content on the screen. The basic difference is that Label support mnemonics (shortcut keys) while Textblock does not. If you do not want shortcut features, you can simply use Textblock as it is lightweight and also supports text wrapping which label does not.

6. What is the different between RadioButton and CheckBox in WPF?

You can do grouping in RadioButton but not in CheckBoxes.

For example: If you place 3 radio buttons in a stack panel, all the radio buttons in that stack panel are grouped i,e you can select any one of them but that feature is not there in CheckBoxes.

Note: Button, RadioButton and CheckBox are derived from ButtonBase class. Further, RadioButton and CheckBox are derived from ToggleButton class.

7. What is the different between Tooltip and Popup in WPF?

There are many differences between WPF Tooltip and Popup:

A) You cannot put user interactive controls in Tooltip as it cannot accept focus but same is possible in Popup.

B) Tooltip is opened and closed automatically when mouse is hovered but Popup does not.

8. How will you get the list of all the fonts installed on your system in WPF?

I will use static SystemFontFamilies collection defined in the System.Windows.Media.Fonts class.

foreach (FontFamily fontFamily in Fonts.SystemFontFamilies)
{
  lstFonts.Items.Add(fontFamily.Source);
}

9. What is the lexicon file in WPF? What is its use?

Lexicon file with exetension .lex is used to create customize the dictionary which is used for spell checking feature in WPF. In your WPF application, when you enable spell checking feature, WPF uses its default dictionary to recognize the words. If you want to add some extra words to that dictionary, you will have to create a lexicon file and add your words there. WPF supports dictionaries in English, German, Spanish and French.

10. What is the difference between Resource Files and Content Files in WPF?

1. Resource files are embedded into the assembly (exe or dll) while content files do not embed with assembly.

2. Content files are used instead of resource files in following scenarios:

A) You want to change the resource file without recompiling the application.
B) The resource file is very large.
C) The resource file is optional and may not be deployed with the assembly.
B) The resource file is a sound file.

How to make a resource file? Just add a file (say any image file) and set its Build Action to Resource (which is by default) in Properties Window.

How to make a content file? Just add a file (say any image file) and set its Build Action to Content in Properties Window. Set Copy to Output Directory to Copy Always.

For example: Suppose you have added a .jpg file of 30KB to your application as a resource. After you Build your application, you will notice an increase of approximately 30KB size in your exe. But if you use same file as content, there will be no increase in the size of exe, but you will notice that same file will be copied in the exe directory.

Related articles: I have written two posts on commonly asked WPF questions and answers. If you are looking for something like that, you can visit Part 1 and Part 2.

Tuesday, June 3, 2014

WPF XAML: Property-Attribute and Property-Element Syntax for Simple and Complex Properties

WPF XAML: Property-Attribute and Property-Element Syntax for Simple and Complex Properties

Property-Attribute and Property-Element are the two approaches in WPF XAML to set the properties of the elements. I will take a very simple example to clear the concepts of both of the Property-Attribute and Property-Element approaches. Lets try to set the background property of the grid. I want to fill the background of the grid with some gradient color. Lets see how can we do this using XAML in WPF?

Suppose I have to set the background of the grid to Green. I will set it like this:

<Grid Name="MyGrid" Background="Green">
....
....
</Grid>

In the above case, I have used Property-Attribute syntax for setting the Background property. WPF has used default brush and painted the area with solid color. But what if you want to use some complex brush and want to paint the background with gradients instead of simple solid color? 

In this scenario, you will have to use Property-Element syntax defined in WPF XAML. Property-Element syntax is represented as ElementName.PropertyName. For example, you have to use Background property in this case as Grid.Background.

So, to introduce gradients in my example, I will have to use LinearGradientBrush instead of the default brush used by WPF for solid fill.

<Grid Name="MyGrid">
  <Grid.Background>
    <LinearGradientBrush>
     <LinearGradientBrush.GradientStops>
       <GradientStop Offset="0.00" Color="Red" />
<GradientStop Offset="0.50" Color="Indigo" />
<GradientStop Offset="1.00" Color="Violet" />
     </LinearGradientBrush.GradientStops>
</LinearGradientBrush>
  </Grid.Background>
</Grid>

In the above example, I have chosen different gradient colors (Red, Indigo and Violet) to paint the background of the Grid.

With this, I think I have cleared the concept of Property-Attribute and Property-Element syntax used in WPF XAML.

Monday, June 2, 2014

WPF XAML Namespaces, Prefixes and Conventions

WPF XAML Namespaces, Prefixes and Conventions

In WPF, XAML contains namespaces for defining controls for your XAML document. You can also map other .NET namespaces to XML namespaces and use them in XAML document. There are some conventions for using prefixes with these namespaces in XAML. Lets go point to point to explore everything about XAML namespaces, prefixes used with namespaces and conventions for using prefixes in XAML.

<Window x:Class="SampleApplication.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="MainWindow" Height="350" Width="525">
  <Grid>       
  </Grid>
</Window>

1. xmlns attribute is a specialized attribute in the world of XML that is reserved for declaring namespaces.

2. The above default XAML code contains two XAML namespaces. 

http://schemas.microsoft.com/winfx/2006/xaml/presentation contains all the WPF classes, including the controls you use to build your user interface. This namespace is declared without any prefix, so this is the default namespace for the entire XAML document. Every element in XAML document, is automatically placed in this namespace unless you specify otherwise.

http://schemas.microsoft.com/winfx/2006/xaml includes various XAML utility features. This namespace is mapped to the prefix "x". That means you can apply it by placing prefix "x" before the element name.

3. The above namespaces are not URI unlike in XML.

4. You can also include .NET namespaces like System in XAML for string manipulation. Syntax for including external namespaces in XAML is:

xmlns:Prefix="clr-namespace:Namespace;assembly=AssemblyName"

For example, you can include System namespace in XAML like this:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Now you can use sys in your XAML document like this:

<sys:DateTime>10/30/2014 5:30 PM<sys:DateTime>

Similarly you can include you custom namespace that you have created in your project like this:

xmlns:local="clr-namespace:MyWPFApplication"

5. Prefix Conventions: In the above examples, I have take x, sys and local prefixes for declaring namespaces. You can take any prefix of your choice, but you should not do it because WPF says to follow this convention for prefixes while declaring XAML namespaces.

Saturday, May 31, 2014

WPF XAML, Loose XAML and BAML Files: Approaches to create WPF applications with XAML

WPF XAML, Loose XAML and BAML Files: Approaches to create WPF applications with XAML

There are four approaches to create WPF application with XAML. You can use XAML directly to in WPF application or can convert XAML into the BAML for improving its performance or you can use loose XAML or do not use XAML at all. Lets try to understand these approaches of creating WPF applications with XAML.

Code and compiled markup(BAML): This is the preferred approach for WPF applications. This approach is used by Visual Studio. You can create XAML template for each window, and this XAML is compiled into BAML and embedded in a final assembly. At runtime, the compiled BAML is extracted and is used to generate the user interface.

Code and uncompiled markup(XAML): You can use this approach when you are creating highly dynamic user interface. In this approach, you load the user interface from a XAML file at runtime using the XamlReader class from the System.Windows.Markup namespace.

Code only: This is the traditional approach used in Visual Studio for Windows Forms application. It generates the user interface through the code statements.

XAML only (Loose XAML): Loose XAML is the file which only contains XAML code without any .NET namespaces, classes, properties, event handlers etc. Loose XAML can be used to stand alone user interface which includes WPF declarative features like animations, triggers, data binding, and links (which can point to other loose XAML files). You can compare loose XAML files with static HTML files. You can open loose XAML files in the Internet Explorer. 

Following points should be considered while creating a loose XAML file:

A) Remove the Class attribute on the root element.
B) Remove any attribute that attach event handlers.
C) Change the name of the opening and closing tag from Window to Page. Internet Explorer can show only hosted pages, not stand-alone windows. 

WPF Layout Controls/Containers, Layout Process, Properties and Tips

WPF Layout Controls/Containers, Layout Process, Properties and Tips

All the WPF Layout containers are panels that derive from the abstract System.Windows.Controls.Panel class. Mainly, there are five layout containers in WPF:

1. StackPanel
2. WrapPanel
3. DockPanel
4. Grid
5. Canvas

I am not going to explain working of all these panels as it is already very well explained here. I will add some extra details about these layout controls in WPF. I will go through WPF Layout Process Stages (Measure Stage and Arrange Stage), how can we create our custom layout containers using MeasureOverride() and ArrangeOverride() methods, different WPF layout properties and some tip and noteworthy points about WPF layout containers.

WPF Layout Process

WPF Layout takes place in two stages:

A) Measure Stage: The container loops through its child elements and asks them to provide their preferred size.
B) Arrange Stage: The container places the child elements in the appropriate position.

Creating WPF Custom Layout Containers

The Panel class also has a bit of internal plumbing you can use if you want to create your own layout containers. Most notably, you can override the MeasureOverride() and ArrangeOverride() methods inherited from FrameworkElement to change the way the panels handle measure stage and arrange stage when organizing its child elements.

WPF Layout Properties

1. Layout Properties of Layout Containers are HorizontalAlignment, VerticalAlignment, Margin, Width, Height, MinWidth, MinHeight, MaxWidth and MaxHeight

2. Default HorizontalAlignment for a Button is Stretch and for a Label is Left.

3. You can set margin for each side of a control in the order left, top, right and bottom. For example:

<Button Margin="1,2,3,4">OK</Button>

In this case, Left Margin = 1, Top Margin = 2, Right Margin = 3 and Bottom Margin = 4.

4. DesiredSize Property: You can find out the size that button wants by examining  the DesiredSize property, which returns the minimum width or the content width, whichever is greater.

5. ActualWidth and ActualHeight Properties: You can find out the actual size used to render an element by reading the ActualHeight and ActualWidth properties. But those values may change when window is resized or the content inside it changes.

6. SizeToContent Property: You can create automatically sized window in WPF if you are creating a simple window with dynamic content. To enable automatic window sizing, remove the Height and Width properties of Window and set the Window.SizeToContent property to WidhtAndHeight. The window will make itselft just large enough to accommodate all its contents. You can also allow a window to resize itself in just one dimension by using the SizeToContent value of Width or Height.

7. Border CornerRadius Property: CornerRadius property allows you to gracefully round the corners of your border. The greater the corner radius, the more dramatic the rounding effect is.

8. WPF Elements should not be explicitly sized.

9. There are three values for visiblity enumeration for elements:

A) Visible: Element is visible
B) Hidden: Element is invisible but the space occupied by it is still reserved.
C) Collapsed: Element is invisible and it also does not take up any space.

WPF Layout Containers - Tips and Noteworthy Points

1. Default orientation of StackPanel is Vertical while default orientation of WrapPanel is Horizontal.

2. DockPanel LastChildFill Property: LastChildFill when set to true, tells the DockPanel to give the remaining space to the last element.

3. DockPanel, Grid and Canvas uses Attached Properties. DockPanel has one attached property: DockPanel.Dock. Grid has two attached properties: Grid.Row and Grid.Column. Canvas has four attached properties: Canvas.Top, Canvas.Left, Canvas.Right and Canvas.Bottom.

4. Grid ShowGridLines Property: ShowGridLines property when set to true, shows all the border of cell and rows.

5. If you don't specify Grid.Row property to the child elements, those child elements are placed on row number 0. Same is the case with Grid.Column.

6. The Grid supports three sizing categories:

A) Absolute Sizes: <ColumnDefination Width="100"></ColumnDefination>
B) Automatic Sizes: <ColumnDefination Width="Auto"></ColumnDefination>
C) Proportional Sizes: <ColumnDefination Width="*"></ColumnDefination>

You can also add weight to proportional sizes: 

<ColumnDefination Width="*"></ColumnDefination>
<ColumnDefination Width="2*"></ColumnDefination>

It means, the second column is twice as bigger as the first one.

7. You can also span rows and columns in a grid.

<Button Grid.Row="0" Grid.Column="0" Grid.RowSpan="2">RowSpannedButton</Button> 

<Button Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2">RowSpannedButton</Button>

8. You can add GridSplitter to a Grid to give the user ability to resize rows and columns.

9. You can also create uniform grids in WPF. Uniform Grids don't require any row and column definition. Example:

<UniformGrid Rows="2" Columns="2">
<Button>Top Left</Button>
<Button>Top Right</Button>
<Button>Bottom Left</Button>
<Button>Bottom Right</Button>
</UniformGrid>

10. All the layout containers can be nested.

11. Canvas is the most lightweight layout container. 

12. Canvas allows you to place elements by using exact coordinates which is a poor choice of designing rich data-driven form.

13. Canvas.ClipToBounds property is used to clip the contents which fall outside the canvas.

14. Canvas.ZIndex property is used when there are overlapping elements in Canvas. The child element having greater ZIndex value will be shown above other child elements.

15. InkCanvas is used to allow stylus input. InkCanvas lets the user annotate contents with strokes.

Friday, May 30, 2014

WPF XAML and BAML: XAML Introduction, Advantages and Compilation

WPF XAML and BAML: XAML Introduction, Advantages and Compilation

This article on WPF XAML covers basic concepts of XAML, Advantages of using XAML into WPF, how XAML elements are related with .NET classes and how XAML in actually compiled in WPF applications. We will get an idea on how WPF XAML code is converted into the BAML and again how BAML code is converted into the XAML and the role of InitializeComponent() method in the process.

XAML stands for Extensible Application Markup Language and is mainly used to create WPF user interface. XAML is also used in Silverlight and WF (Windows Workflow Foundation). You can create XAML using Visual Studio as well as Expression Blend. Basically Visual Studio is for developers and Expression Blend is for designers.

Advantage of XAML in WPF applications

In WPF, due to the introduction of XAML, graphical designer can separately work on user interface and developers can concentrate on the main logic. But it was not possible in Windows Form because any visual element such as label, textbox, button you create in Windows Forms are defined in C# classes. So, the designer could not do anything in that. All the user interface thing had to be taken care by developer itself. Designers could make separate mock-ups for screens in Photoshop etc. which developers had to convert in the C# code which was very much painful. But WPF XAML changed the world. Now designers can directly make screens for developers in XAML and developers just have to bind the elements in the screen with the properties they have made in their C# code.

Relation between XAML Elements and .NET Classes

Every element in XAML document maps to an instance of .NET class. The name of the element matches to the name of the .NET class. For example, the element Button in XAML instructs WPF to create an object of Button class in .NET. XAML element attributes are used to set the properties of .NET classes. 

Note: XAML is case-sensitive language. 

For example: You cannot write below XAML code
<Button Content="Hit Me"></Button>
like this
<button Content="Hit Me"></button>

Conversion of XAML into BAML: XAML Compilation

When you compile your WPF application, all your XAML code is converted into the BAML (Binary Application Markup Language) by XAML parser and is embedded as a resource into the final DLL or EXE. BAML is nothing but the binary representation of XAML. BAML is tokenized, which means lengthier bits of XAML are replaced with shorter tokens. Not only BAML is significantly smaller, but it is also optimized in a way that makes it faster to parse at runtime.

Conversion of BAML into XAML: The InitializeComponent() Method

InitializeComponent() method plays a vital role in WPF applications. Therefore, you should never delete InitializeComponent() call in your window's constructor. Similarly, if you add another constructor to your window class, make sure it also calls InitializeComponent().

InitializeComponent() calls LoadComponent() method of the System.Windows.Application class. The LoadComponent() method extracts the BAML(the compiled XAML) from your assembly and uses it to build your WPF user interface.