Thursday, July 23, 2015

ObservableCollection and BindingList

Difference between ObservableCollection and BindingList
An ObservableCollection can be updated from UI exactly like any collection. The true difference is rather straightforward:
ObservableCollection<T> implements INotifyCollectionChanged which provides notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated.
However, BindingList<T> implements IBindingList.
IBindingList provides notification on collection changes, but not only that. It provides a whole bunch of functionality which can be used by the UI to provide a lot more things than only UI updates according to changes, like:
Sorting
Searching
Add through factory (AddNew member function).
Readonly list (CanEdit property)
All these functionalities are not available in ObservableCollection<T>
Another difference is that BindingList relays item change notifications when its items implement INotifyPropertyChanged. If an item raises a PropertyChanged event, the BindingList will receive it an raises a ListChangedEvent with ListChangedType.ItemChanged and OldIndex=NewIndex (if an item was replaced, OldIndex=-1). ObservableCollection doesn't relay item notifications.
Note that in Silverlight, BindingList is not available as an option: You can however use ObservableCollections and ICollectionView (and IPagedCollectionView if I remember well).

Use of Using keyword

Use of Using keyword
The reason for the "using" statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
The .NET CLR converts
using (MyResource myRes = new MyResource()) { myRes.DoSomething(); }
to
// limits scope of myRes  
MyResource myRes= new MyResource();  
try 
{ myRes.DoSomething(); }  
finally {  
// Check for a null resource.  
if (myRes!= null) // Call the object's Dispose method. 
((IDisposable)myRes). Dispose(); } }

BeginInVoke and InVoke

BeginInVoke,  InVoke
  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

    stilll under developemt ...

Static and Dynamic Resource

Static and Dynamic Resource
A resource can be referenced as either static or dynamic resource. This can be done by using either Static resource markup extension or Dynamic resource markup extension. You can go through my post on Markupextension in WPF for more information about markup extension.

  1. The major difference between static and dynamic resources is “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 used those.
  4. If resource is defined on the element’s resources and the same element property is using the resource defined inside its resources then static resource not applied because it should appears afterwards. The same thing is valid for dynamic resource. Let’s have a look on below code snippet.
      Below code gives compile time error.
      <Grid Background="{StaticResource lightBlueColor}">
        <Grid.Resources>
           <SolidColorBrush Color="LightBlue" x:Key="lightBlueColor"/>
        </Grid.Resources>
      </Grid>
         The same is valid for dynamic resource
      <Grid Background="{DynamicResource lightBlueColor}">
        <Grid.Resources>
           <SolidColorBrush Color="LightBlue" x:Key="lightBlueColor"/>
        </Grid.Resources>
      </Grid>

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

XAML
<Window.Resources>
   <SolidColorBrush Color="LightBlue" x:Key="buttonBackground" />
</Window.Resources>
<StackPanel Name="stkPanel">
   <Button Name="Button1" Content="Button1"
           Width="150" Height="40" Margin="5"
           Background="{StaticResource buttonBackground}"/>
   <Button Name="Button2" Content="Button2"
           Width="150" Height="40" Margin="5"
           Background="{DynamicResource buttonBackground}"/>
   <Button Name="Button3" Content="Button3"
           Width="150" Height="40" Margin="5"
           Background="{StaticResource buttonBackground}"/>
</StackPanel>

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

Output

Style in WPF

Style

A Style is a group of Setter and Trigger actions that affect properties of the styled object.
A Setter is an action that sets a specified property to the specifed value. A Style possess a collection of Setter actions which are automatically applied (called Setters).
A Trigger is an action which, as its name indicates, is triggerred by a particular condition. Depending on the Trigger type, a Trigger can contain Setters or Storyboards. A Style possesses a collection of Trigger actions, rightfully called Triggers.
<Style x:Key="DialogButtonStyle" TargetType="Button">
    <Setter Property="Template">
       <Setter.Value>
           <ControlTemplate TargetType="{x:Type Button}">
               <Grid>
                   <Ellipse Fill="{TemplateBinding Background}"
                            Stroke="{TemplateBinding BorderBrush}"/>
                       <ContentPresenter HorizontalAlignment="Center"
                                         VerticalAlignment="Center"/>
               </Grid>           
           </ControlTemplate>
       </Setter.Value>
    </Setter>
</Style>
<Button Style="{StaticResource DialogButtonStyle}" />

Style vs. Template: What is the difference?

Style is used to set the properties of an object to particular values. In addition, a Style allows Triggers based on styled object events, styled object property values, and data values. In turn, triggers allow the animation of the object's properties.
In contrast, a Template is used to define the Visual Tree of a Control (ControlTemplate) or the Visual Tree of the representation of an object (DataTemplate). While templates also have Triggers, it is to be noted that Style triggers cannot interact with particular items of the Visual Tree for the object.
One common distinction of Styles and Templates states that a Style can contain one/many Setters/Triggers to change the ControlTemplate or DataTemplate of controls/objects.

DataTemplate, ControlTemplate

DataTemplate: What is it?

A DataTemplate provides the Visual representation of a single data item (a data object).

DataTemplates are mostly used in the context of ItemsControl and ContentControl (and their derived classes) to determine how data items need to be displayed.

The following is an example of using a DataTemplate:

If we need to display a list of dates, we could use a ListBox (ItemsControl) and set its Items property to a list of DateTime objects.

The ListBox would display each date according to their default representation (text string). However, for our particular needs, we want each date to be represented by three different TextBlock controls, each with a different background, stacked one on top of the other vertically. This can be done by setting the ItemTemplate (of type DataTemplate) of the ListBox to a custom DataTemplate.

<DataTemplate DataType="{x:Type s:DateTime}">
  <StackPanel>
    <TextBlock Text="{Binding Path=Year}" Background="Red" />
    <TextBlock Text="{Binding Path=Month}" Background="Blue" />
    <TextBlock Text="{Binding Path=Day}" Background="Green" />
  </StackPanel>
</DataTemplate>

ControlTemplate: What is it?

A ControlTemplate defines the Visual Tree of a control.

All standard controls come with a default template, but if the default representation of the control lacks details or does not match your needs, you can create another template for the control and apply the template to that control.

Also, when creating a custom control, you'll most probably want to override the default ControlTemplate inherited from the base class.