Sunday 29 September 2013

WPF Knowledge - Part3 (XAML Concept)


In Previous post, We have gone thru WPF features, properties, uses/comparison with windows form , In general, have got better idea about WPF. Now, we should concentrate more on basic WPF elements which are required to build up an XAML application.

As we know that our WPF UI is made of using XAML, So now we need to understand more about XAML and how we can use XAML element and attribute more effectively by binding property.

Already explain about XAML and BAML theoretically in WPF Knowledge Part1 and WPF Knowledge Part2 respectively. Now, we will discuss here on practical concept of XAML in WPF application



What are the New XAML features in WPF 4.0 and above?                                 
     1.   Easy Object References with {x:Reference}
    <!-- XAML 2006 -->     
    <Label Target="{Binding ElementName=firstName}">FirstName</Label>
    <TextBox x:Name="firstName" />

    <!-- XAML 2009 -->
    <Label Target="{x:Reference firstName}">FirstName</Label>
    <TextBox x:Name="firstName" />

    2.   Built-In Type – No need to include namespace in XAML 2009
     <!-- XAML 2006 -->
     <sys:String xmlns:sys="clr namespace:System;assembly=mscorlib >
                                                                                           Test</sys:String>
     <!-- XAML 2009 -->
     <x:String>Test</x:String>
 
The following types are included into the XAML language: 
 <x:Object/>, <x:Boolean/>, <x:Char/>, <x:String/>, <x:Decimal/>,  <x:Single/>, <x:Double/>, <x:Int16/>, <x:Int32/>, <x:Int64/>, <x:TimeSpan/>, <x:Uri/>, <x:Byte/>, <x:Array/>, <x:List/>, <x:Dictionary/>

     3.   Generics in XAML with x:TypeArguments – No need to define class employee in XAML 2009
   class EmployeeCollection : ObservableCollection<Employee>{} <!-- XAML 2006 -->
   <l:EmployeeCollection>
       <l:Employee FirstName="John" Name="Doe" />
       <l:Employee FirstName="Tim" Name="Smith" />
   </lEmployeeCollection>
 
   <ObservableCollection x:TypeArguments="Employee"<!-- XAML 2009 -->
       <l:Employee FirstName="John" Name="Doe" />
          <l:Employee FirstName="Tim" Name="Smith" />
       </ObservableCollection />

    4.   Support for Arbitrary Dictionary Keys
    <!-- XAML 2006 -->
    <StreamGeometry x:Key="CheckGeometry">
                      M 0 0 L 12 8 l 9 12 z</StreamGeometry>

     <!-- XAML 2009 -->
    <StreamGeometry>M 0 0 L 12 8 l 9 12 z
        <x:Key><x:Double>10.0</x:Double></x:Key>
    </StreamGeometry>

     5.   Use of Non-Default Constructors with x:Arguments – Can pass constructor argument using x:argument
    <DateTime>  00:00:00.0000100   </DateTime>                <!-- XAML 2006 -->
    
    <DateTime>                                                                           <!-- XAML 2009 -->
            <x:Arguments><x:Int64>100</x:Int64></x:Arguments>
    </DateTime>


     6.   Use of Static Factory Methods with x:FactoryMethod – No need to create a Static variable, simple pass a factory method in XAML 2009
   Guid id = Guid.NewGuid();                                                       <!-- XAML 2006 -->

   <Guid x:FactoryMethod="Guid.NewGuid" />                             <!-- XAML 2009 -->          
 

Name the Built-in MarkUp extension in WPF?
       1.   Binding – Two bind the value of two property together
       2.   Static Resource – One Time look up of a resource entry
       3.   Dynamic Resource – Auto updating look up of a resource entry
       4.   Relative Resource -
       5.   Template Binding – To bind a property of a control template to a 
           dependency property of a control
       6.   x:Type – Used to define the type of an object during runtime
       7.   x:Static – Resolve a value of the static property
       8.   x:Null – return null


Difference between x:Key and x:Name
x:Key and x:Name, both are the XAML attributes that are specified in the declaration of XAML elements. 
  1. x:Name is used to mention the names of StyleSheets as well as the user interface controls while x:Key  It is used mainly with the WPF Stylesheets or in ResourceDictionaries. 
  2. x:Name can also be accessed in the code-behind (.xaml.cs /.xaml.vb) while x:Key cannot be accessed in code behind
  3. x:Name is applicable for user interface elements  line button, label while x:Key is not applicable.


What is X:Code
       1.   x:Code is a directive element defined in XAML. 
       2.   An x:Code directive element can contain inline programming code. 
       3.   The code that is defined inline can interact with the XAML on the same page.


What is XPath and Uses ?
XPath stands for xml Path. It’s language used to access different part of xml document such as element and attribute.


What is Path animation?
Ans: Path animation in which the object moves along the path specified by the Path geometry. As the animation progresses, it reads the X-axis, Y-axis and angle information from the path geometry and generates the output. These are useful when an object has to be animated along a complex path.


What is difference between DataContext and ItemSource?

1.  DataContext is mainly used to hold common data that other child want to share. Usually, DataContext is set explicitly at the top of the hierarchy, and sometimes overriden (re-bound explicitly) lower in the hierarchy no matter directly or indirectly. Most of the time, ItemsSource will be bound to a member of DataContext (either direct or indirect, as a sub-property of a property of the DataContext).

2.  All the descendants of FrameworkElement can utilize the DataContext property and set an object to its value But ItemsSource is the property identifying the source for templated generation of items in an ItemsControl

3. DataContext expects an object type where ItemsSource expects IEnumerable type objects.

4. DataContext Tells an element what data it is going to bind and ItemSource which does the binding.

5.  DataContext is not enough to bind an ItemsControl to a list. You need to bind ItemsSource to achieve auto-generation of items in the list.

6.  DataContext is a dependency property is exposed by FrameworkElement base class where as ItemSource is defined by the control (HierarchicalDataTemplate)




What are the Types of Resources in WPF?
  1) Binary Resources: Binary resources could be logo/image files, AV files etc.
  2) Logical Resources are of two types:  Static Resources and Dynamic Resources



 
What is the Choice between StaticResource and DynamicResource in WPF?
StaticResource finds the key defined within the ResourceDictionary under its scope during the Loading of the application. Hence the Compiler will throw error during compilation if not found in resources while DynamicResource Markup Extension defers the resource assignment to the actual runtime of the application. So the expression remains unevaluated until the object being created.
       1.   StaticResource requires less CPU during runtime, so it is faster.
       2.   StaticResource are created when the application loads. So making everything as StaticResource means slowing down the Application Load process. 
       3.   When the resources are unknown during compilation, you can use DynamicResource. 
       4.   DynamicResource are used when user interaction changes the look and feel of an object.

Note: The demerit of DynamicResource is that it reduces application performance because resources are retrieved every time they are used. The best practice is to use StaticResource until there is a specific reason to use DynamicResource.



First WPF Application

Window1.xaml

<Window x:Class="WpfApplication1.Window1"
   
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   
Title="Window1" Height="300" Width="300">
   
<Grid>
   
</Grid>
</Window>


Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
//…more using statements

namespace WpfApplication1
{
   
/// <summary>
   
/// Interaction logic for Window1.xaml
   
/// </summary>
   
public partial class Window1 : Window
   
{
       
public Window1()
       
{
           
InitializeComponent();
       
}
   
}
}


App.xaml

<Application x:Class="WpfTutorialSamples.App"
             
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             
StartupUri="MainWindow.xaml">
   
<Application.Resources>

   
</Application.Resources>
</Application>

App class used to start an application, StartupUri is used to startup the main file   


App.xaml.cs

using System;
using System.Collections.Generic;
using System.Windows;

namespace WpfTutorialSamples
{
       
public partial class App : Application {}
}


What is the diff. between User Settings and Application Settings in WPF?User Settings are Read/Write, they can be read or write even at runtime and can be saved while Application Settings are read-only, they can only be written at design time.



    What is application object and its responsibility?
1.   Application is a class that represents a WPF application running as a standalone client application in Windows. 
2.   Each running application contains at most a single instance of Application. 

    The Application object is defined in the App.xaml file and is responsible for: 

1.   Managing application lifetime (e.g. r esponding to startup/shutdown events) 
2.   Window, property and resource management 
3.   Command-line processing 

4.   Navigation



Important Window properties

The WPF Window class has a bunch of interesting attributes that you may set to control the look and behavior of your application window. Here's a short list of the most interesting ones:
Icon - Define icon of the window, shown in the upper right corner, right before the window title.

ResizeMode – Window resize mode, by default is CanResize, have othee resize mode loke  CanMinimize, CanMaximiz, NoResize

ShowInTaskbar - The default is true, but if you set it to false, your window won't be represented in the Windows taskbar. Useful for non-primary windows or for applications that should minimize to the tray

SizeToContent - Decide if the Window should resize itself to automatically fit its content. The default is Manual, if set  to Auto then other options like Width, Height and WidthAndHeight, will automatically adjust with window size

Topmost - The default is false, but if set to true, your Window will stay on top of other windows unless minimized. Only useful for special situations.

WindowStartupLocation - Controls the initial position of your window. The default is Manual, Other options are CenterOwner, which will position the window in the center of it's owner window, and CenterScreen,

WindowState - Controls the initial window state. It can be either Normal, Maximized or Minimized. The default is Normal


Best Practices

      1. Avoid fixed positions - use the Alignment properties in combination   
          with Margin to position elements in a panel.
      2. Avoid fixed sizes - set the Width and Height of elements 
          to Auto whenever possible.
      3. Don't use the canvas panel to layout elements. Use it only for vector 
          graphic.
      4. Use a StackPanel to layout buttons of a dialog.
      5. Use a GridPanel to layout a static data entry form. Create a Auto sized 
          column for the labels and a Star sized column for the TextBoxes.  
      6. Use an ItemControl with a grid panel in a DataTemplate to layout 
          dynamic key value lists. Use the SharedSize feature to synchronize the 
          label widths.



Reference:
      1.       MSDN
      2.       http://wpftutorial.net
      3.       www.dotnetfunda.com/
      4.    http://www.wpf-tutorial.com