Tuesday, June 14, 2016

Introduction of Behaviors

Behaviors encapsulate the pieces of functionality into a reusable component, so that can attach to a element.


To be more clear - Suppose we have a Text box, and the requirement is when there is data in the text box the background will be green other wise white.

for simply without behaviour we can achieve this by writing some event and code for this, but if the same this is needed for many Text boxes for different UI, we need to write the code again and again. (It is a very simple example but real scenario can be more complex)
Behaviour just wrap this functionality and can be attach with element if needed with element.

Behaviour introduces in Expression Blend 3 (System.Windows.interactivity.dll)

Benefit -
Behavior is to provide additional functionalities and extensibility to controls without writing code in the code-behind.

Behaviors also have the benefit of keeping the MVVM pattern intact, since we can move code from code behind to behaviours.

Behaviour is reusable component, write once and use later as many time is required.


Implementation
TO create a Behavior  Just drive your class with Behavior<T>(Behavior Generic class) and there is a method OnAttached override it.

Behavior is the base class for providing attachable state and commands to an object. The types the Behavior can be attached to can be controlled by the generic parameter. Override OnAttached() and OnDetaching() methods to hook and unhook any necessary handlers from the AssociatedObject.(Source MSDN)

public abstract class Behavior<T> : Behavior where T : DependencyObject

There is two important method OnAttached() and OnDetaching() in Behaviour class, this can be override to implement Behavior.


Behavior can be simple and with command.


E.g
Lets we have a situation where we need Textbox , if there is data the background turn to Green other wise it is Red.

Create a Behavior class TextChangeBehaviour.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace BehavoiurTest
{
    public class TextChangeBehaviour : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
           TextBox txtBox= AssociatedObject as TextBox;
           txtBox.TextChanged += txt_TextChanged;
           if (string.IsNullOrEmpty(txtBox.Text))
           {
               txtBox.Background = new SolidColorBrush(Colors.Green);
           }
           else
           {
               txtBox.Background = new SolidColorBrush(Colors.Red);
           }
           
        }

        void txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox txtBox = AssociatedObject as TextBox;
            txtBox.TextChanged += txt_TextChanged;

            if (string.IsNullOrEmpty(txtBox.Text))
           {
               txtBox.Background = new SolidColorBrush(Colors.Green);
           }
           else
           {
               txtBox.Background = new SolidColorBrush(Colors.Red);
           }
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            TextBox txtBox = AssociatedObject as TextBox;
            txtBox.TextChanged -= txt_TextChanged;
          
        }
    }
}


To attach this behaviour with Text box, suppose we have a window TextChangeBhehaviourTest.xaml

<Window x:Class="WpfApplication1.TextChangeBhehaviourTest"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:TxtChBhe="clr-namespace:BehavoiurTest"
        xmlns:e="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        Title="TextChangeBhehaviourTest" Height="300" Width="300">
    <Grid>
        <TextBox Width="150" Height="25">
            <e:Interaction.Behaviors>
                <TxtChBhe:TextChangeBehaviour></TxtChBhe:TextChangeBehaviour>
            </e:Interaction.Behaviors>
        </TextBox>
    </Grid>
</Window>



here we need to add assembly of Interactivity, and Behaviour.

Thursday, June 9, 2016

Understanding Resources in WPF


In WPF Resources are use to define object in XAML to reuse in Application.
Resources are not the part of visual three, but can be used in XAML to provide value to the XAML property attributes. Resources can be create and access in XAML and Code in both side viceversa.
E.g.  Suppose need an object of solidcolorbrush for background of some buttons with same color.
One option we can create it in XAML

<Window x:Class="WPFResources.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"
        xmlns:clrType="clr-namespace:System;assembly=mscorlib">
    <Window.Resources>
        <SolidColorBrush x:Key="myColorBrush" Color="Red"/>
    </Window.Resources>
</Window>

This resource is created under window resource dictionary
Now any button (any ui control) can use this resource in this window

<Window x:Class="WPFResources.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"
        xmlns:clrType="clr-namespace:System;assembly=mscorlib">
    <Window.Resources>
        <SolidColorBrush x:Key="myColorBrush" Color="Red"/>
    </Window.Resources>
    <Grid>
        <Button Background="{StaticResource myColorBrush }"/>
        <Ellipse Fill="{StaticResource myColorBrush }"/>
        <Grid Background="{StaticResource myColorBrush }"></Grid>
    </Grid>
</Window>

Resource can be declared in
  1.      App.XAML
  2.       Resource Property of the current window
  3.       Resources property of any FrameworkElement or FrameworkContentElement
  4.       Separate XAML File 
  • As global application scope within the application App.xaml file
  • As Window level scope within the Resources property of the current Window
  • Within the Resources property of any FrameworkElement or FrameworkContentElement.
  • Separate XAML resource file.
In App Level in App.XAML file

<Application.Resources>
        <SolidColorBrush x:Key="MyColorBrush" Color="Red"></SolidColorBrush> 
    </Application.Resources>

Window Level

<Window x:Class="WpfApplication1.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">
    <Window.Resources>
        <SolidColorBrush x:Key="MyColorBrush" Color="Red"></SolidColorBrush>
    </Window.Resources>  
</Window>

Stack Level

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:clrType="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <SolidColorBrush x:Key="MyColorBrush" Color="Red"></SolidColorBrush>
    </Window.Resources>
    <StackPanel>
        <StackPanel.Resources>
            <clrType:String x:Key="strText">Hello</clrType:String>
        </StackPanel.Resources>
        <TextBox Text="{StaticResource strText}"></TextBox>
    </StackPanel>

</Window>


Friday, June 3, 2016

WPF Binding

Introduction

Data binding is the mechanism to flow the Data from source to target and vice versa. This mechanism provide a way to update the user interface when there is change in data in ViewModel side.

A 'Binding' can only be set on a DependencyProperty of a DependencyObject






Data binding can be Unidirectional or Bidirectional.







Binding work along with Notification mechanism on both side.

.Net Property: in this side, use INotifyPropertyChanged interface to raise the PropertyChanged event.
Dependency Property:  In this side, PropertyChanged callback of the property metadata is in Action.

Binding Mode

Binding mode describes the direction of the data flow in a binding.

Default

The default value varies for each dependency property. In general, user-editable control properties, such as those of text boxes and check boxes, default to two-way bindings, whereas most other properties default to one-way bindings

OneTime :Update the binding target when the application start or when the data context change.

OneWay :Update the biding target from source not vice versa.

OneWayToSource Update the source from binding target not vice versa.

TwoWay : This binding to ensure data synchronization between source and target, when any change in source reflect in target and any change in target reflect in source.


In XAML {Binding} mark up extension is use for Data Binding.

<Grid>
<Label Content=”Binding [.Net Property of ViewModel]” />
e.g.  FirstName is the property in the View Model and want to bind with Lable
<Label Content=”Binding FirstName” /> 
</Grid>


Markup Extension
https://msdn.microsoft.com/en-us/library/ms747254(v=vs.100).aspx

Common markup extension specific to WPF only.

  1. StaticResource
  2. DynamicResource
  3. Binding
  4. RelativeSource
  5. TempletBinding
  6. ColorConvertedBitmap
  7. ComponentResourceKey
  8. ThemeDictionary

Some Terminology

Source: View Model Property (.Net property)
Target: UI (XAML) DP property

...In progress