Friday, 23 August 2019

ObservableCollection in WPF


ObservableCollection:

1. An ObservableCollection is a dynamic collection of objects of a given type.

2. Objects can be added, removed or be updated with an automatic notification of actions. 

3. When an object is added to or removed from an observable collection, the UI is automatically updated. 

4. This happens because, when binding to an observable collection, WPF automatically adds a CollectionChanged event handler to the ObservableCollecion's events.

5. An ObservableCollection works essentially like a regular collection except that it implements the interfaces:
INotifyCollectionChanged,
INotifyPropertyChanged

6. As such it is very useful when you want to know when the collection has changed. 

7. An event is triggered that will tell the user what entries have been added/removed or moved.

8. More importantly they are very useful when using databinding on a form.

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Documents;

namespace MyObservable
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<Person> person; // Declare ObservableCollection with Person class

        public MainWindow()
        {
            InitializeComponent();

            //In the Minwindow constructor, we are adding 2 persons(Param,Smith)
            person = new ObservableCollection<Person>()
            {
                new Person() { FirstName = "G", LastName = "Param", Age =36, Address = "India", ZipCode = "530041"},
                new Person() {FirstName = "P", LastName = "Smith", Age =40, Address = "US", ZipCode = "555212"}
            };
            lstNames.ItemsSource = person;//lstNames is listbox, we have taken in the MainWindow.xaml

        }

        private void btnNames_Click(object sender, RoutedEventArgs e)
        {
            int age = 0;
            int.TryParse(txtAge.Text, out age);

            person.Add(new Person() { FirstName = txtFName.Text, LastName = txtLName.Text, Age = age, Address = txtAddress.Text, ZipCode = txtZipCode.Text });

            txtFName.Text = string.Empty;
            txtLName.Text = string.Empty;
            txtAge.Text = string.Empty;
            txtZipCode.Text = string.Empty;
            txtAddress.Text = string.Empty;
        }
    }

    //eg: Person contains 5 properties as below
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string ZipCode { get; set; }
    }
}

MainWindow.xaml:

<Window x:Class="MyObservable.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Observable Collection" Height="300" Width="400">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Grid.Column="0" Margin="5,5,5,5">
            <TextBlock x:Name="lblFName" Text="First Name"></TextBlock>
            <TextBox x:Name="txtFName"></TextBox>
            <TextBlock x:Name="lblLName" Text="Last Name"></TextBlock>
            <TextBox x:Name="txtLName"></TextBox>
            <TextBlock x:Name="lblAge" Text="Age"></TextBlock>
            <TextBox x:Name="txtAge"></TextBox>
            <TextBlock x:Name="lblAddress" Text="Address"></TextBlock>
            <TextBox x:Name="txtAddress"></TextBox>
            <TextBlock x:Name="lblZipCode" Text="ZipCode"></TextBlock>
            <TextBox x:Name="txtZipCode"></TextBox>
            <Button Grid.Column="0" Width="100" Height="20" Margin="5,5,5,5" x:Name="btnNames" Click="btnNames_Click" Content="Add"></Button>
        </StackPanel>

        <ListView x:Name="lstNames" Margin="5,5,5,5" Grid.Column="1" Grid.Row="0">
            <ListView.View>
                <GridView x:Name="grdNames">
                    <GridViewColumn Header="First Name"  DisplayMemberBinding="{Binding FirstName}"/>
                    <GridViewColumn Header="Last Name"  DisplayMemberBinding="{Binding LastName}"/>
                    <GridViewColumn Header="Age"  DisplayMemberBinding="{Binding Age}"/>
                    <GridViewColumn Header="Address"  DisplayMemberBinding="{Binding Address}"/>
                    <GridViewColumn Header="ZipCode"  DisplayMemberBinding="{Binding ZipCode}"/>
                </GridView>
            </ListView.View>
        </ListView>
        
    </Grid>

</Window>


Normal CLR Property and Dependency Property in WPF

Normal CLR Property and Dependency Property in WPF

Normal CLR Property:

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

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);
    }
}

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.

1. 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.

2. 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.

3. 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.


Wednesday, 14 August 2019

MemoryCache vs ObjectCache in .net 4.0


MemoryCache vs ObjectCache :

MemoryCache is the concrete implementation of ObjectCache.

1. ObjectCache is abstract and demonstrates how a cache should be built.
2. MemoryCache is the actual implementation of ObjectCache