Tuesday, January 21, 2014

Difference between WPF and Window Forms in .NET

Difference between WPF and Window Forms in .NET

I have been asked the difference between WPF and Window Forms. my times by my juniors whenever I suggest them to learn WPF. So, today I am trying to clear this doubt and make my opinions clear about this.

There are a lot of differences between WPF and Window Forms. WinForms is past and WPF is the latest technology equipped with advanced features which Window Forms lack. WPF supports UI, media, documents, hardware acceleration, vector graphics, scalability to different form factors, interactive data visualization, and superior content readability. Lets have a look on the features and benefits that WPF provides over the Window Forms.

1. WPF is a Vector Graphics based UI Presentation Layer

WPF is a vector graphics based UI presentation layer where WinForms is not. By being vector based, it allows the presentation layer to smoothly scale UI elements to any size without distortion.

2. Enhanced Custom Controls Support

WPF is also a composable presentation system, which means that pretty much any UI element can be made up of any other UI element. This allows you to easily build up complex UI elements from simpler ones.

3. Enhanced DataBinding Support

WPF is also fully databinding aware, which means that you can bind any property of a UI element to a .NET object (or a property/method of an object), a property of another UI element, or data. Yes, WinForms supports databinding but in a much more limited way.

4. WPF is "skinable" or "themeable"

WPF is "skinable" or "themeable", which means that as a developer you can use a list box because those are the behaviors you need but someone can "skin" it to look like something completely different.

Think of a list box of images. You want the content to actually be the image but you still want list box behaviors. This is completely trivial to do in WPF by simply using a listbox and changing the content presentation to contain an image rather than text.
 
5. Supports Window Forms

WPF does support Windows Forms and Windows Forms can be included in WPF project by adding dlls of Window Forms.

Conclusion:

WPF is a replacement for WinForms. What Window Forms can do, WPF can, but what WPF can do, Window Forms cannot do all.

INotifyPropertyChanged Interface and PropertyChangedEventHandler in WPF

INotifyPropertyChanged Interface and PropertyChangedEventHandler in WPF

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, which a property value has changed. The INotifyPropertyChanged interface contains an event called PropertyChanged. Whenever a property on a ViewModel / Model  object has a new value, it can raise the PropertyChanged event to notify the WPF binding system of the new value. Upon receiving that notification, the binding system queries the property, and the bound property on some UI element receives the new value

public class MyClass:INotifyPropertyChanged
{
    private int _ID;
    private string _Name;

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public int ID
    {
        get
        {
            return _ID;
        }
        set
        {
            _ID = value;
            OnPropertyChanged("ID");
        }
    }
    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }
}

Difference Between Dependency Property and Normal CLR Property in WPF

Difference Between Dependency Property and Normal CLR Property in WPF

The Normal CLR property and the dependency property look quite similar but the dependency property is more powerful and has more features. In WPF, dependency properties are used in Animation, Styles, Triggers, Templates, Validation, Data Binding, Layout etc.

Syntax Difference Between Dependency Property and Normal CLR Property

Syntax of Normal CLR Property

private int count;
public int Count
{
   get
   {
      return count;
   }
   set
   {
      count = value;
   }
}

Syntax of Dependency Property

public static DependencyProperty PageSizeProperty =
DependencyProperty.RegisterAttached("PageSize",
typeof(int), typeof(AttachedPropertySample),
             new PropertyMetadata(25,
             new PropertyChangedCallback(OnPageSizePropertyChanged)));

public int PageSize
{
    get
    {
        return (int) GetValue(PageSizeProperty);
    }
    set
    {
        SetValue(PageSizeProperty, value);
    }
}

In Built Change Notification

Dependency provides change notification when its value has been changed. You can specify Call Back while registering dependency property so user will get notification. This is mainly used in Data Binding. But CLR property has not any inbuilt change notification. So if you want your normal CLR proprety also notify changes, you have to implement INotifyPropertyChanged.

Value Resolution

CLR property reads value directly from private member while dependency property dynamically resolves value when you call GetValue() method of dependency property. The GetValue and SetValue methods are inherited from Dependency Object.

Value Inheritance

If you specify dependency property to top element it will be inherited to all child elements until child element specifically override the property. Dependency property value is resolved at runtime when you call GetValue() method. 

Suggestion: If your property will commonly be the source of a databinding (e.g. providing the Text for a TextBlock), I would recommend using a standard CLR property and having the containing class implement INotifyPropertyChanged.

Difference between Dependency Property and Attached Property in WPF

Difference between Dependency Property and Attached Property in WPF

Attached properties are a type of dependency property. But there is a minor difference between dependency property and attached property in WPF. Lets try to understand them.

1. Concept and Usage of Attached Property and Dependency Property

Attached properties allows container to create a property which can be used by any child UI elements whereas dependency property is associated with that particular elements and can help in notification of changes and reacting to that changes.

Attached properties are basically meant for the container elements.like if you have a grid and you have grid.row, now this is considered to be an attached property of a grid element. Also you can use this property in texbox, button etc to set its place in the grid.

Attached properties are used a lot for layout-related information. For example, Canvas needs Left/Top coordinates, Grid needs a Row and a Column, DockPanel needs a Dock information etc. It would be a mess if all of this had to be declared on every control that can be layouted. So they are declared on the corresponding panel, but used on any control.

2. Implementation of Attached Property and Dependency Property

Attached properties and normal dependency properties include the methods used to register them with the DependencyObject. 

For attached properties, DependencyProperty.RegisterAttached andDependencyProperty.RegisterAttachedReadOnly are used and for dependency propertiesDependencyProperty.Register and DependencyProperty.RegisterReadOnly are used.

The difference between DependencyProperty.Register() and DependencyProperty.RegisterAttached() is that .Register() is used to register a 'regular' dependency property on a DependencyObject, while .RegisterAttached() is used to set an 'attached' dependency property.

Difference between StaticResource and DynamicResource in WPF

Difference between StaticResource and DynamicResource in WPF

There are lot of differences between Static Resource and Dynamic Resource in WPF. Lets try to understand them with the help of examples below:

1. The major difference between static and dynamic resources is that static resource will evaluate the resource only once while dynamic resource will be evaluated every time the resource needed.

2. Dynamic resource has more performance overhead than static resources because it look up for resources every time it requested or needed.

3. Static resource is faster but it takes little more time to load page or window than dynamic resource because dynamic resources are loaded when you actually use them.

Example of Static and Dynamic Resources

Below example gives you clear picture about Static and Dynamic resource markup extension.

XAML

   
   
            Background="{StaticResource buttonBackground}"/>
   
            Background="{DynamicResource buttonBackground}"/>
   
            Background="{StaticResource buttonBackground}"/>

Code behind

void StaticAndDynamicResources_Loaded(object sender, RoutedEventArgs e)
{
    stkPanel.Resources["buttonBackground"] = Brushes.Yellow;
}

Output

As shown in above example, three buttons are using buttonBackground resource defined in windows.resources element. Button1 and Button3 are using static resource markup extension while button2 is using dynamic resource markup extension. After loading of my window, I have changed color of buttonBackground resource from Lightblue to Yellow in code behind. So when I run my application, Button2 will have yellow background and rest of the buttons will have LightBlue background. The reason behind for not changing background of Button1 and Button3 because both button uses static resource and static resource is loaded only once with application while button2 uses dynamic resource and it changes every time when it accessed. 

Conclusion: 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.

Binding Modes in WPF

Binding Modes in WPF: TwoWay, OneWay, OneTime and OneWayToSource

The Mode attribute defines the binding mode that will determine how data flows between the source and the target. There are four types of binding modes in WPF:

1. TwoWay Binding Mode
2. OneWay Binding Mode
3. OneTime Binding Mode
4. OneWayToSource Binding Mode

1. TwoWay Binding Mode

You have the view connected with its ViewModel, so every change you make in one of them is reflected into the other. To obtain that kind of behavior, you have to implement the interface INotifyPropertyChange in your ViewModel or using Dependency Properties, instead of normal CLR properties.The default however is two-way.

This type of binding is appropriate for editable forms or other fully-interactive UI scenarios. Most properties default to OneWay binding, but some dependency properties (typically properties of user-editable controls such as the Text property of TextBox and the IsChecked property of CheckBox) default to TwoWay binding. A programmatic way to determine whether a dependency property binds one-way or two-way by default is to get the property metadata of the property using GetMetadata and then check the Boolean value of the BindsTwoWayByDefault property.

2. OneWay Binding Mode

In one way mode, data flows from the source to the target each time a change is made on the source (ViewModel). OneWay binding is the default binding mode for the TextBlock's Text property and does not need to be specified. 

This type of binding is appropriate if the control being bound is implicitly read-only. For instance, you may bind to a source such as a stock ticker or perhaps your target property has no control interface provided for making changes, such as a data-bound background color of a table. If there is no need to monitor the changes of the target property, using the OneWay binding mode avoids the overhead of the TwoWay binding mode.

3. OneTime Binding

Like OneWay binding, OneTime binding sends data from the source to the target; however, it does this only when the application is started. When the DataContext changes, it does not listen for change notifications in the source. 

OneTime binding causes the source property to initialize the target property, but subsequent changes do not propagate. This means that if the data context undergoes a change or the object in the data context changes, then the change is not reflected in the target property. This type of binding is appropriate if you are using data where either a snapshot of the current state is appropriate to use or the data is truly static. This type of binding is also useful if you want to initialize your target property with some value from a source property and the data context is not known in advance. This is essentially a simpler form of OneWay binding that provides better performance in cases where the source value does not change.

4. OneWayToSource Binding Mode

OneWayToSource is the reverse of OneWay binding. Unlike OneWay and OneTime binding, OneWayToSource binding sends data from the target to the source.