Showing posts with label Dependency Object. Show all posts
Showing posts with label Dependency Object. Show all posts

Thursday, July 14, 2011

Updating Source in WPF Data Binding


In WPF data binding, when source property is updated from target property is called as updating source property and is defined using UpdateSourceTrigger property of Binding object. This property is used to define how you want to update source. There are two binding modes are available TwoWay and OneWayToSource which causes update to source property on change of target property.







You can specify mainly three different values to UpdateSourceTrigger property of Binding. If you don’t specify any value to UpdateSourceTrigger it uses default.

PropertyChanged – It updates source property as soon as target property changed.

<TextBox Name="CustomerName" Height="30" Margin="5"
        Text="{Binding Source={StaticResource MyCustomerData},
        Path=CustomerName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
        Grid.Row="0" Grid.Column="1" />

LostFocus – When target object loses focus as soon as source property is updated.

<TextBox Name="CustomerName" Height="30" Margin="5"
         Text="{Binding Source={StaticResource MyCustomerData},
         Path=CustomerName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"/>

Explicit – Source property is updated when you call explicitly UpdateSource method from code.

<TextBox Name="CustomerName" Height="30" Margin="5"
         Text="{Binding Source={StaticResource MyCustomerData},
         Path=CustomerName, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>

Code:


BindingExpression bindingExpression =
CustomerName.GetBindingExpression(TextBox.TextProperty);
bindingExpression.UpdateSource();



Tuesday, July 12, 2011

Binding Modes in WPF


In WPF data binding, four different types of binding modes are available.

OneWay – When source property changed it will automatically update target property. If you bind CustomerName property to TextBlock or Label it will default establish oneway binding and whenever CustomerName property changes it will update Label’s content property. In this Binding mode target property updated only when source property changed.



TwoWay – When source property changed it will update target property and when target property changed will update source property. If you bind customer name property with TextBox’s Text property using twoway binding mode then whenever user changes text in textbox will update CustomerName property and similarly whenever CustomerName property changes will update Textbox’s text property.



OneTime – This binding mode establish binding only one time when your application starts or when you set DataContext property. This type of mode can be used when you want to display data for first time only.


OneWayToSource – Updates source property on change of target property. This is reverse of OneWay binding. This type of mode is mainly used when your target property is not dependency property.



Default – If you don’t specify any binding mode then default binding will take place. The default binding mode will choose binding mode depending upon target property. For example, if you binding property with Label’s Content property then default binding will be OneWay similarly if you are binding to TextBox’s Text property then default binding will be TwoWay. If you are not sure sometimes it is best to specify binding mode explicitly.  


Related links -
Data Binding in WPF
Dependency Property
WPF Architecture

Monday, July 11, 2011

Data Binding in WPF


What is Databinding?

WPF introduced data binding concept which provides simple and easy way to represent data in application. Data binding establish link between source and target.



As illustrated in above diagram, Binding establish link between source object and target object. When source object updates it notifies target object and when target object updates it notifies source object if binding is set to twoway.

Binding object has four major components Source object, Target object, Source Property and Path. You also specify other properties of binding like Binding Mode, Name etc. While binding target property must be a dependency property.  Almost all UI elements/controls are derived from Dependency object so you can set an element's property as target property of data binding. You can define Binding in XAML file as well in code behind. 


Let’s have a look on simple binding in XAML.

<StackPanel>
   <TextBox Name="MyTextBox" Width="150" Height="35" Text="" />
   <Label Content="{Binding ElementName=MyTextBox, Path=Text}"
          Width="150" Height="35" />
</StackPanel>











Above example demonstrates simple element to element data binding in WPF which one of the simple way to achieve data binding. I bound Label’s Content Property with Textbox’s Text property. Here both properties are dependency properties.  In above example TextBox’s Text property is source of data and Label’s content property is target. Whenever users types something in textbox it will automatically update label’s content.

Let’s have a look on another example here.



<Window x:Class="WpfApplication1.DataBindingDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="Data Binding Demo" Height="150" Width="300">
<Window.Resources>
    <local:CustomerData x:Key="MyCustomerData"
           CustomerName="Mitesh Sureja"  CustomerAddress="Mumbai"/>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="0.15*"/>
        <RowDefinition Height="0.15*"/>
    </Grid.RowDefinitions>
    <TextBlock Text="Customer Name:" Margin="5"
               Grid.Row="0" Grid.Column="0"
               VerticalAlignment="Center" />
    <TextBox Name="CustomerName" Height="30" Margin="5"
        Text="{Binding Source={StaticResource MyCustomerData},
        Path=CustomerName, Mode=TwoWay}" Grid.Row="0" Grid.Column="1" />
    <TextBlock Text="Customer Address:" Margin="5"
               Grid.Row="1" Grid.Column="0"
               VerticalAlignment="Center"/>
    <TextBox Name="CustomerAddress" Height="30" Margin="5"
        Text="{Binding Source={StaticResource MyCustomerData},
        Path=CustomerAddress, Mode=TwoWay}" Grid.Row="1" 
        Grid.Column="1" />
</Grid>
</Window>

public class CustomerData : INotifyPropertyChanged
{
    private string customername;
    public string CustomerName
    {
        get
        {
            return customername;
        }
        set
        {
            customername = value;
            OnPropertyChanged("CustomerName");
        }
    }
    private string customeraddress;
    public string CustomerAddress
    {
        get
        {
            return customeraddress;
        }
        set
        {
            customeraddress = value;
            OnPropertyChanged("CustomerAddress");
        }
    }
    //Implementation of INotifyPropertyChanged Interface
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}












In above example I have bound two properties of CustomerData class to two different TextBox controls. CustomerData class implements InotifyPropertyChanged interface. So whenever CustomerName and CustomerAddress value changed it will notify target control similarly if user changes text in textboxes it will updated CustomerData’s respective properties because of two way binding mode.



You might also like
Dependency Property
Attached Property
WPF Architecture

Thursday, July 7, 2011

Difference between Dependency Property and Normal CLR Property

Dependency Property vs. Normal CLR Property


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.

CLR property Syntax

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

Dependency property syntax

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

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

Major features of Dependency Properties are

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. You can read more about Dependency Property here.

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.

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


You might also like
Dependency Property
Attached Property
WPF Architecture

Wednesday, July 6, 2011

Attached Properties in WPF


Attached properties are special type of dependency properties. The special thing about this property is that they can be set from any object of class other than they are defined. The object on which they are used is called as target object. The common attached properties are Grid.Row, Grid.Column, Canvas.Top, Canvas.Left, DockPanel.Dock, TextElement.FontSize, TextElement.FontWeight etc.

<Grid TextElement.FontStyle="Italic" TextElement.FontWeight="Bold">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.8*" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Label Grid.Row="0" Grid.Column="0"
           Content="Enter value:" VerticalAlignment="Center"
           Margin="5"  />
    <TextBox Grid.Row="0" Grid.Column="1"
             Name="MyText" Height="25" Margin="5" />
    <Button Grid.Row="1" Grid.ColumnSpan="2"
            Content="Save" Height="30" Width="100" />
</Grid>

In above XAML code you can see the use of attached properties like TextElement.FontStyle, TextElement.FontWeight, Grid.Row, Grid.Column etc. You also noticed that these properties are setting from other instances like TextElement.FontStyle attached property value set from Grid similar Grid.Row value set from Label and TextBox etc.

You can also create your own Attached Dependency Property.  

<Window x:Class="WpfApplication1.AttachedPropertyDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="AttachedPropertyDemo" Height="200" Width="250">
    <Window.Resources>
        <local:AttachedPropertySample local:AttachedPropertySample.TextAttachedProperty="Attached Property Test" x:Key="TestAttachedProperty" />
    </Window.Resources>
<Grid>
</Grid>
</Window>

public class AttachedPropertySample : DependencyObject
{
    //Register Attached Property
    public static DependencyProperty MyAttachedProperty =
        DependencyProperty.RegisterAttached("TextAttachedProperty",
        typeof(string), typeof(AttachedPropertySample),
        new PropertyMetadata("Test",
        new PropertyChangedCallback(OnMyAttachedPropertyChanged)));

    //Get Attached Property Value
    public static string GetTextAttachedProperty(
                         AttachedPropertySample attachedSample)
    {
        return (string)attachedSample.GetValue(MyAttachedProperty);
    }

    //Set Attached Property Value
    public static void SetTextAttachedProperty(
                  AttachedPropertySample attachedSample, string value)
    {
        attachedSample.SetValue(MyAttachedProperty, value);
    }
    //On Value change of Attached Property
    public static void OnMyAttachedPropertyChanged(
           DependencyObject dObject, DependencyPropertyChangedEventArgs e)
    {
        MessageBox.Show(e.NewValue.ToString());
    }
}

You can also create Attached ReadOnly Dependency Property for that you need to register dependency property using DependencyProperty.RegisterAttachedReadOnly. This readonly attached properties can be created similar to readonly dependency properties. You can go through my post related dependency property here and checkout how to create readonly dependency properties.


You might also like
Dependency Property
WPF Class Hierarchy
XAML Overview