Friday, December 30, 2011

What's new in XAML of .NET 4.0

hello guys!!!

What's new in XAML of .NET 4.0

Easy Object References with {x:Reference}

If you want to create an object reference today you need to do a databinding and declare the source with an ElementName. In XAML 2009 you can use the new {x:Reference} markup extension



Built-in Types

If you want to add objects of simple types like string or double to a resource dictionary today you need to map the needed clr-namespaces to an XML namespaces. In XAML 2009 we a lot of simple types that are included in the XAML language.

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

The following types are included into the XAML language:

Generics in XAML with x:TypeArguments

If you want to use an ObservableCollection in XAML you need to create a type that derives fromObservableCollection because you cannot declare it in XAML. With XAML 2009 you can use the x:TypeArgumentsattribute to define the type of a generic type.

   class EmployeeCollection : ObservableCollection { }        FirstName="John" Name="Doe" />     FirstName="Tim" Name="Smith" />     x:TypeArguments="Employee">     FirstName="John" Name="Doe" />     FirstName="Tim" Name="Smith" />     

Support for Arbitrary Dictionary Keys

In XAML 2006 all explicit x:Key value were threated as strings. In XAML 2009 you can define any type of key you like by writing the key in ElementSyntax.

   x:Key="CheckGeometry">M 0 0 L 12 8 l 9 12 z    M 0 0 L 12 8 l 9 12 z     10.0     

Use of Non-Default Constructors with x:Arguments

In XAML 2006 objects must have a public default constructor to use them. In XAML 2009 you can pass constructor arguments by using the x:Arguments syntax.

   00:00:00.0000100                  100          

Use of Static Factory Methods with x:FactoryMethod

When you have a type that has no public constructor but a static factory method you had to create that type in code in XAML 2006. With XAML 2009 you can use the x:FactoryMethodx:Arguments attribute to pass the argument values.

   Guid id = Guid.NewGuid();    x:FactoryMethod="Guid.NewGuid" />    

What's new in XAML of .NET 4.0

Easy Object References with {x:Reference}

If you want to create an object reference today you need to do a databinding and declare the source with an ElementName. In XAML 2009 you can use the new {x:Reference} markup extension

   ="{Binding ElementName=firstName}">FirstName x:Name="firstName" />    ="{x:Reference firstName}">FirstName x:Name="firstName" />    

Built-in Types

If you want to add objects of simple types like string or double to a resource dictionary today you need to map the needed clr-namespaces to an XML namespaces. In XAML 2009 we a lot of simple types that are included in the XAML language.

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

The following types are included into the XAML language:

Generics in XAML with x:TypeArguments

If you want to use an ObservableCollection in XAML you need to create a type that derives fromObservableCollection because you cannot declare it in XAML. With XAML 2009 you can use the x:TypeArgumentsattribute to define the type of a generic type.

   class EmployeeCollection : ObservableCollection { }        FirstName="John" Name="Doe" />     FirstName="Tim" Name="Smith" />     x:TypeArguments="Employee">     FirstName="John" Name="Doe" />     FirstName="Tim" Name="Smith" />     

Support for Arbitrary Dictionary Keys

In XAML 2006 all explicit x:Key value were threated as strings. In XAML 2009 you can define any type of key you like by writing the key in ElementSyntax.

   x:Key="CheckGeometry">M 0 0 L 12 8 l 9 12 z    M 0 0 L 12 8 l 9 12 z     10.0     

Use of Non-Default Constructors with x:Arguments

In XAML 2006 objects must have a public default constructor to use them. In XAML 2009 you can pass constructor arguments by using the x:Arguments syntax.

   00:00:00.0000100                  100          

Use of Static Factory Methods with x:FactoryMethod

When you have a type that has no public constructor but a static factory method you had to create that type in code in XAML 2006. With XAML 2009 you can use the x:FactoryMethodx:Arguments attribute to pass the argument values.

   Guid id = Guid.NewGuid();    x:FactoryMethod="Guid.NewGuid" />    

Saturday, November 19, 2011

WPF and Silverlight Layout Controls

The WPF and Silverlight platforms have a wide selection of powerful layout controls. This topic will provide you with an understanding of these layout controls and how to take advantage of the WPF and Silverlight Designer features when working with these controls. In this topic when the term pixel is used, it refers to a device-independent-pixel. In WPF a pixel is 1/96 of an inch. This MSDN topic covers device-independent-pixels. http://msdn.microsoft.com/en-us/library/bb847924.aspx

Table of Contents


  1. Layout Control Types
  2. Panel Selection
  3. Panels
  4. Grid
  5. StackPanel
  6. Canvas
  7. DockPanel
  8. WrapPanel
  9. UniformGrid
  10. Panel.ZIndex
  11. Decorators
  12. Border
  13. Content Controls
  14. Window
  15. UserControl
  16. GroupBox
  17. Expander
  18. TabItem
  19. Items Controls
  20. TabControl
  21. Layout Properties
  22. Comments

Layout Control Types

WPF layout controls can be logically grouped by base types that determine their behavior.

  1. Panels

    1. Provide arrangement of their child objects.
    2. Derive directly or indirectly from Panel.
    3. Have a Children property that is a collection of their child objects.
    4. Example controls are the Grid, StackPanel, Canvas, DockPanel WrapPanel and UniformGrid.
  2. Decorators

    1. Apply effects to their single child object.
    2. Derive from Decorator.
    3. Have a Child property that contains their single child object.
    4. Example controls are the Border and ViewBox
  3. Content Controls

    1. Contain a single object of any type.
    2. Derive directly or indirectly from ContentControl.
    3. Have a Content property that contains their single object.
    4. Example controls are the Window, UserControl, GroupBox, TabItem, Expander, HeaderedContentControl and ContentControl.
  4. Items Controls

    1. Used to present a collection of objects.
    2. Derive directly or indirectly from ItemsControl.
    3. Have two ways of being populated

      • Objects can be added to the Items property in code behind or in XAML.
      • A list of objects can be bound to the ItemsSource property.
    4. When objects are added using either of the two above methods, UI objects will be automatically generated. The generated UI objects can be customized through the use of DataTemplates.
    5. Example controls are the ListBox, ListView, DataGrid, TabControl, ComboBox, Menu and ItemsControl.
  5. See for the further details...

Friday, November 18, 2011

Exceptions and Validation

Validation is only a concern for TwoWay data bindings. When Silverlight moves data from your view back into your model – how do you control the values your model accepts? And how do you inform the user when they’ve entered illegal input?

First, let’s talk about the problems that can occur when data flows back into your model. The first potential problem is that Silverlight may not be able to convert the user’s input into the data type the model requires. This can happen when the user types “abc” into a field that expects integers, or types “123” into a field that requires a date. Some of these problems you try to avoid by using restricted controls (a calendar control for the user to enter a date, as an example), but this won’t avoid all conversion problems.

Another type of problem happens when Silverlight can convert the user’s input into the proper type, but your business logic determines the value of the data is illegal. One example is trying to place an order for –1 books. You want the quantity value of an order to always be positive. In these cases you must your model throw an exception when Silverlight sets the value. How do you know the exception occurred?

Silverlight can tell you about both types of validation errors, but you must set two properties on a binding to true. The first property is the ValidatesOnExceptions property. This property tells Silverlight to catch exceptions that occur when data moves from the view to the model. Again – this will be the exceptions thrown when trying to convert the user’s input, AND any exceptions thrown by the model itself.

In order to know about these exceptions you must also set the NotifyOnValidationError property to true. When true, Silverlight will raise a BindingValidationError event. This event will bubble up the visual tree of elements, so you can subscribe to the event on the element that is data bound, or at the element’s parent level, or the parent’s parent, and so on. In the following XAML we subscribe at the UserControl level.

<UserControl Width="400"      x:Class="DataBindingDemo.EditTimeCard"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"      xmlns:local="clr-namespace:DataBindingDemo"      BindingValidationError="UserControl_BindingValidationError" >     <UserControl.Resources>         <local:DateFormatter x:Key="dateFormatter" />     UserControl.Resources>     <Grid x:Name="LayoutRoot" Background="White">         <StackPanel>             <TextBlock Text="Total Hours"/>             <TextBox Margin="10" Text="{Binding                                          ValidatesOnExceptions=true,                                         NotifyOnValidationError=true,                                         Mode=TwoWay,                                         Path=TotalHours}"/>             <TextBlock Text="Start Date"/>              <TextBox Margin="10" Text="{Binding                                         Mode=TwoWay,                                         Converter={StaticResource dateFormatter},                                         ConverterParameter='{0:d}',                                         Path=PayPeriod.Start}"/>             <TextBlock Text="End Date"/>             <TextBox Margin="10" Text="{Binding Path=PayPeriod.End}"/>                     StackPanel>     Grid> UserControl> 

The BindingValidationError event can tell you the source of an error, and also if the error is being added (the user just entered bad input) or removed (the user corrected a bad input). We can use this information to change elements on the screen, such as making the control that is the source of the failure turn red.

private void UserControl_BindingValidationError(     object sender, ValidationErrorEventArgs e) {     var control = e.OriginalSource as Control;     switch (e.Action)     {         case ValidationErrorEventAction.Added:             control.Background = new SolidColorBrush(_red);             break;         case ValidationErrorEventAction.Removed:             control.Background = new SolidColorBrush(_white);             break;     } } 

The DataGrid

Grids play a prominent role in many applications, and Silverlight includes a DataGrid control in the System.Windows.Controls.Data assembly. You can drag this control from the Visual Studio Toolbox window into your XAML file and Visual Studio will take care of referencing the correct assemblies and adding the proper XML namespace definitions to your XAML file. The DataGrid supports editing, sorting, and drag n’ drop columns. The DataGrid, like the ListBox, has an ItemsSource property we can use to set a binding expression. Simply setting up the binding after placing the grid in your XAML is enough to get started, as the grid is capable of auto-generating columns from the model (the grid will create a column for every public property).

<data:DataGrid AutoGenerateColumns="True"                 HeadersVisibility="All"                ItemsSource="{Binding}"                                       RowBackground="Cornsilk"                 AlternatingRowBackground="BlanchedAlmond"                ColumnWidth="85" RowHeight="30"                IsReadOnly="True" CanUserResizeColumns="False">         data:DataGrid>

Simple customizations of the grid are possible just by setting some properties - background colors, grid lines, and resizable columns. For more control you can define the exact columns you want the grid to use by setting the Columns property. The Silverlight grid includes three types of columns: a GridTextColumn (to display text), a DataGridCheckBoxColumn (great for boolean properties), and a DataGridTemplate column. Like most templates in Silverlight, you can use a DataGridTemplate column to display nearly anything you want inside a grid – use calendars, stack panels, colored rectangles, etc. Notice the TimeCards column in the above screen shot. That grid is using auto-generated columns and doesn’t know how to display a property that is a collection. Now look at the following XAML:

<Grid x:Name="LayoutRoot" Background="White">     <data:DataGrid AutoGenerateColumns="False"                            ItemsSource="{Binding}"                                   IsReadOnly="False">         <data:DataGrid.Columns>             <data:DataGridTextColumn Binding="{Binding Name}" Width="50" />             <data:DataGridTemplateColumn>                 <data:DataGridTemplateColumn.CellTemplate>                     <DataTemplate>                         <data:DataGrid AutoGenerateColumns="True"                                         ItemsSource="{Binding TimeCards}"/>                      DataTemplate>                 data:DataGridTemplateColumn.CellTemplate>             data:DataGridTemplateColumn>         data:DataGrid.Columns>     data:DataGrid> Grid> 

In the above XAML we’ll turn off auto-generated columns and explicitly define the columns for display. Using the DataGridTemplateColumn we can even define a nested data grid to display all the time cards for an employee. For more information about the grid control, I highly recommend the following blog posts.

Also, be aware of a “bug” in the Silverlight 2.0 version of the DataGrid. Jesse Liberty describes the problem in his post “It Ain’t You, Babe … A Not-a-bug Bug in DataGrid”. The problem is that validation errors are tricky to catch with the DataGrid. Let’s look at validation next.