WPF Questions

In this aritcle on "Commonly Asked WPF Interview Questions and Answers (Part 1)", I will focus on very simple and basic WPF interview questions which a WPF developer should know. These WPF interview questions are based on general introduction of WPF, XAML, MVVM Pattern, Comparison of WPF and Silverlight, Layout Panels in WPF and WPF UserControls / CustomControls.

 
1. What is WPF?

 
The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.

 
WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

 
2. What is XAML?

 
Extensible Application Markup Language, or XAML (pronounced "zammel"), is an XML-based markup language developed by Microsoft. XAML is the language behind the visual presentation of an application that you develop in Microsoft Expression Blend, just as HTML is the language behind the visual presentation of a Web page. Creating an application in Expression Blend means writing XAML code, either by hand or visually by working in the Design view of Expression Blend.

 
3. What is MVVM Pattren?

 
Model-View-ViewModel (MVVM) pattern splits the User Interface code into 3 conceptual parts - Model, View and ViewModel.

 
Model is a set of classes representing the data coming from the services or the database.

 
View is the code corresponding to the visual representation of the data the way it is seen and interacted with by the user.

 
ViewModel serves as the glue between the View and the Model. It wraps the data from the Model and makes it friendly for being presented and modified by the view. ViewModel also controls the View's interactions with the rest of the application

 
4. What is the difference between MVVM and MVC patterns?

 
MVVM Model-View ViewModel is similar to MVC, Model-View Controller.

 
The controller is replaced with a View Model. The View Model sits below the UI layer. The View Model exposes the data and command objects that the view needs. You could think of this as a container object that view goes to to get its data and actions from. The View Model pulls its data from the model.

 
5. What are the similarities and differences between WPF and Silverlight?

 
Similarities between Silverlight and WPF

 
1. Silverlight and WPF both use XAML.
2. Silverlight and WPF share same syntax, code and libraries.


 
Difference between WPF and Silverlight

 
1. WPF  is tool for writing full-featured desktop applications that run on Windows while Silverlight is for web application.

2. WPF competes with Windows Forms only for writing desktop applications while Silverlight competes with Flash, Java web apps etc.

 
6. What is the need of layout panels in WPF?

 
Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel coordinates may work for an limited enviroment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail. WPF provides a rich set built-in layout panels that help you to avoid the common pitfalls.

 
7. What are the different types of layout panels in WPF?

 
There are mainly 5 types of layout panels in WPF. These are: 

 
Grid Panel
Stack Panel
Dock Panel
Wrap Panel
Canvas Panel


 
 
8. How to create a User Control and then how to use it in a WPF application?

 
User Controls are commonly used in a WPF application. So you should know this concept and you should be able to write a simple program to show how usercontrols are created and used in WPF application. I am sharing a link which created and uses usercontrol in very simple manner. Have a look:

 
 
9. What is the difference between UserControl and CustomControl in WPF?
 

UserControl (Composition)

 
Composes multiple existing controls into a reusable "group"
Consists of a XAML and a code behind file
Cannot be styled/templated
Derives from UserControl


 
CustomControl (Extending an existing control)

 
Extends an existing control with additional features
Consists of a code file and a default style in Themes/Generic.xaml
Can be styled/templated
The best approach to build a control library

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.

Difference between Window and Page Controls in WPF?

In this article on "Difference between Window and Page Controls in WPF", I will try to explain the difference between window and page controls used in WPF. Both controls have different usage depending on different requirements of the application. Lets try to understand this difference.

1. Window Control (Window.xaml) are used for Windows Application while Page Control (Page.xaml) is used for making Browser Hosted Applications. Page can be implemented as root element in Xaml file and can contain single element similar to window.

<Page x:Class="WpfApplication1.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Page1">
      Welcome to WPF Page Navigation.
</Page>

Similar to normal xaml file you can specify page name StartupUrl inside App.xaml to open specific page.

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="Page1.xaml">
</Application>

2. Page Control can be contained in Window Control but vice versa is not possible

You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). 

WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.

Frame class provides inbuilt support NavigationFramework. Let’s have a look on below code.

<StackPanel>
    <TextBlock Margin="10">This is Main Window.</TextBlock>
    <Frame Margin="10"
        Source="Page1.xaml"
            JournalOwnership="OwnsJournal"></Frame>
</StackPanel>

Dependency Property and Dependency Object: Difference between Dependency Propery and CLR Property

Dependency properties belong to one class but can be used in another. Consider the code snippet below:

<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" /> 

Height and Width are regular properties of the Rectangle. But Canvas.Top and Canvas.Left are dependency properties as they belong to the Canvas class. It is used by the Rectangle to specify its position within Canvas.

Dependency Property is defined as static. So Dependency Property is maintained at class level. The wrapper class which can create a Dependency property is called a DependencyObject. To work with dependency property, you must derive the class from DependencyObject

Difference between Dependency property and CLR property

CLR property is just a wrapper around private variables. It uses Get / Set methods to retrieve and store value of a variable into it. CLR property gives you only one block in which you can write code to invoke whenever a property is get or set. Hence CLR property system is fairly straightforward.

On the other hand, the capabilities of Dependency property system is huge. The idea of Dependency property is to compute the value of the property based on the value of other external inputs. The external inputs might be styles, themes, system properties, animations, etc. So, you can say a dependency property works with most of the WPF inbuilt features that were introduced.

Advantages of Dependency Property

1. Property Value Inheritance: By Property Value Inheritance, we mean that value of a Dependency property can be overridden in the hierarchy in such a way that the value with highest precedence will be set ultimately.

2. Data Validation: We can impose Data Validation to be triggered automatically whenever the property value is modified.

3. Participation in Animation: Dependency property can animate. WPF animation has lots of capabilities to change value at an interval. Defining a dependency property, you can eventually support Animation for that property.

4. Participation in Styles: Styles are elements that define the control. We can use Style Setters on Dependency property.

5. Participation in Templates: Templates are elements that define the overall structure of the element. By defining Dependency property, we can use it in templates.

6. DataBinding: As each of the Dependency properties itself invoke INotifyPropertyChanged whenever the value of the property is modified, DataBinding is supported internally. 

7. CallBacks: You can have callbacks to a dependency property, so that whenever a property is changed, a callback is raised.

8. Resources: A Dependency property can take a Resource. So in XAML, you can define a Resource for the definition of a Dependency property.

9. Metadata overrides: You can define certain behavior of a dependency property using PropertyMetaData. Thus, overriding a metadata form a derived property will not require you to redefine or re implementing the whole property definition.

10. Designer Support: A dependency property gets support from Visual Studio Designer. You can see all the dependency properties of a control listed in the Property Window of the Designer.

How To Define a Dependency Property

public static readonly DependencyProperty MyCustomProperty = 
DependencyProperty.Register("MyCustom", typeof(string), typeof(Window1));
public string MyCustom
{
    get
    {
        return this.GetValue(MyCustomProperty) as string;
    }
    set
    {
        this.SetValue(MyCustomProperty, value);
    }
}

In the above code, I have simply defined a Dependency property. Dependency property is declared as static and maintained in class level, so you may say Class A to have a property B. So property B will be maintained to all the objects that class A have individually. The Dependency property thus creates an observer for all those properties maintained by class A and stores it there. Thus it is important to note that a Dependency property should be maintained as static.

The naming convention of a dependency property states that it should have the same wrapper property which is passed as the first argument. Thus in our case, the name of the Wrapper "MyCustom" which we will use in our program should be passed as the first argument of the Register method, and also the name of the Dependency property should always be suffixed with Property to the original Wrapper key. So in our case, the name of the Dependency Property is MyCustomProperty. If you don't follow this, some of the functionality will behave abnormally in your program.

It should also be noted that you should not write your logic inside the Wrapper property as it will not be called every time the property is called for. It will internally call the GetValue and SetValue itself. So if you want to write your own logic when the dependency property is fetched, there are callbacks to do them.

Attached Properties in WPF: Special Kind of Dependency Properties

Attached properties are a special kind of DependencyProperties. They allow you to attach a value to an object that does not know anything about this value.

A good example for this concept are layout panels. Each layout panel needs different data to align its child elements. The Canvas needs Top and Left, The DockPanel needs Dock, etc. Since you can write your own layout panel, the list is infinite. So you see, it's not possible to have all those properties on all WPF controls.

The solution are attached properties. They are defined by the control that needs the data from another control in a specific context. For example an element that is aligned by a parent layout panel.

To set the value of an attached property, add an attribute in XAML with a prefix of the element that provides the attached property. To set the the Canvas.Top and Canvas.Left property of a button aligned within a Canvas panel, you write it like this:

<Canvas>
    <Button Canvas.Top="20" Canvas.Left="20" Content="Click me!"/>
</Canvas>
 
public static readonly DependencyProperty TopProperty =
    DependencyProperty.RegisterAttached("Top", 
    typeof(double), typeof(Canvas),
    new FrameworkPropertyMetadata(0d,
        FrameworkPropertyMetadataOptions.Inherits));
 
public static void SetTop(UIElement element, double value)
{
    element.SetValue(TopProperty, value);
}
 
public static double GetTop(UIElement element)
{
    return (double)element.GetValue(TopProperty);
}

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

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");
        }
    }
}
 
Types of Routed Events in WPF
 
The concept of Routed Events comes into the picture when we want to handle an event, that is originated from some other control in the hierarchy.  Say for example if any user clicks the button control, that event which is normally a button_click event, can be raised by button, label, gird or window.
 
Types of Routed Events:
 
WPF defines most routed events in pairs - one tunnelling and the other bubbling.
 
1. Direct Events
2. Bubbling Events
3. Tunneling Events
 
1.  Direct Events:
 
Direct Events are very well known to .NET people who has worked on standard .NET controls.  A direct event get raised by the control itself. Say for example button_click event which got raised by the button control itself.
 
2.  Bubbling Events:
 
Bubbling events are first raised by the control and then are raised by the controls in that control's hierarchy. Say in a window, we have a grid and in that we have a button control. Now if button is clicked, first it will raise button_click event, then the grid event and at last the window event.
 
3.  Tunneling Events:
 
The Tunneling Events are the opposite of the bubbling events as they are raised first by the root element in the hierarchy and then by the child elements. Same as our previous example, first window event will get raised, followed by the grid event and at last the button_click event.
 
The tunnelling event name always begins with 'Preview' and is raised first. This gives parents the chance to see the event before it reaches the child. This is followed by the bubbling counterpart. In most cases, you will handle only the bubbling one.
 
Example of Routed Events
 
Routed Events provide the ability for different controls in the element tree to react to events.
For instance, if we have a Window containing a StackPanel containing a Button and someone presses the mouse key on the button, the events will be fired in this order:
 
PreviewMouseDown on Window
PreviewMouseDown on StackPanel
PreviewMouseDown on Button
MouseDown on Button
MouseDown on StackPanel
MouseDown on Window
 
Example with code
 
XAML file:
 
<Grid Button.Click="Grid_Click">
    <StackPanel Button.Click="StackPanel_Click">
        <Button Content="Click Me!" Height="35" Width="150"
        Margin="5" />
    </StackPanel>
</Grid>
 
CodeBehind file:
 
private void StackPanel_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Stackpanel");
}
 
private void Grid_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Grid");
}
 
Now when button is clicked, following messages will appear in sequence
Stackpanel
Grid

Difference between Events and Commands in WPF MVVM Architecture
 
Commands are very powerful and useful feature of WPF. Cut, Copy and Paste are basic inbuilt commands in WPF. Commands and Events are related to each other to a large extent but the main concern there is that events doesn't fit well into MVVM paradigm. So we generally prefer to use commands in WPF MVVM architecture. Commands provide a lot of advantages over events. Some of them are listed below:
 
1. Commands in WPF allow you to move the implementation of a command handler to the buisness layer.

2. You can bind WPF command in the view (XAML) and receive the event raised. This way you do not have to use code behind which is a no-no in MVVM.

3. In events an action is tightly coupled with its source and can't be reused freely; Using commands you can easily maintain various actions in a single place and reuse them anywhere in application.

4. Commands are similar to Events except we can associate any number of UI Controls or Input Gestures to a command and bind that command to a handler that is executed when control are activated or gestures are performed.
 
ICommand Interface and RelayCommand Class in WPF MVVM

ICommand Interface and RelayCommand Class in WPF are commonly used for binding. ICommand Interface and RelayCommand class is implemented in the ViewModel and is exposed to the view controls.

Every view in the app has an empty codebehind file, except for the standard code that calls InitializeComponent in the class's constructor. In fact, you could remove the views' codebehind files from the project and the application would still compile and run correctly. Despite the lack of event handling methods in the views, when the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Hyperlink, Button, and MenuItem controls displayed in the UI. Those bindings ensure that when the user clicks on the controls, ICommand objects exposed by the ViewModel execute. You can think of the command object as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

When a ViewModel exposes an instance property of type ICommand, the command object typically uses that ViewModel object to get its job done.

We will try to understand ICommand Interface and RelayCommand Class with following example.

Create a View and ViewModel like following:

View: Lets create the view first.  Three things to note in this view

1. In this view, I have included MyWPFSample namespace

xmlns:local="clr-namespace:MyWPFSample"

2. I have set datacontext of the winodw to the MainWindowViewModel class present in MyWPFSample namespace

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>    

3. I have done binding of the command of the button with the ButtonCommand property of MainWindowViewModel class.

Command="{Binding ButtonCommand}"

<Window x:Class="MyWPFSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyWPFSample"
        Title="MainWindow" Height="150" Width="370">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
        <Grid>
        <Button Content="Click"
                Height="23"
                HorizontalAlignment="Left"
                Margin="77,45,0,0"
                Name="btnClick"
                VerticalAlignment="Top"
                Width="203"
                Command="{Binding ButtonCommand}"
                CommandParameter="Hai" />
    </Grid>
</Window>


ViewModel: ViewModel has namespace MyWPFSample, class as MainWindowViewModel and property as ButtonCommand. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace MyWPFSample
{
    class MainWindowViewModel
    {
        private ICommand m_ButtonCommand;
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }
        public MainWindowViewModel()
        {
            ButtonCommand=new RelayCommand(new Action<object>(ShowMessage));
        }
        public void ShowMessage(object obj)
        {
            MessageBox.Show(obj.ToString());
        }
    }
}

When the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object acts as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

RelayCommand Class

In this example RelayCommand class is used for implementing ICommad object. I think it's a simple and standard approach.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace MyWPFSample
{
    class RelayCommand : ICommand
    {
        private Action<object> _action;
        public RelayCommand(Action<object> action)
        {
            _action = action;
        }
        #region ICommand Members
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged;
        public void Execute(object parameter)
        {
            if (parameter != null)
            {
                _action(parameter);
            }
            else
            {
                _action("Hello World");
            }
        }
        #endregion
    }
}

ICommand and RelayCommand keep track whether or not commands are available. If commands are not available, then all controls associated with that command are disabled. For example using command controls like button can be disabled if CanExecute() returns false. The Code that executes when command is invoked and is located in Execute event. handler. 
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. 

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

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

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.

TextBox

Tag cloud

    RecentPosts