Thursday, 31 October 2013

WPF VALIDATION - MANOHAR GOUD 9866550012



WPF validation


There are too many ways to validate the WPF controlls. I explain here some of them with example. 
We need a validation to prevent user from entering a wrong details.
Here we used IDataErrorInfo for validation.Validation made easy with IDataErrorInfo. here I explain you how we used IDataErrorInfo in WPF for validating the controlls. If we are using binding property to bind the contrlss with the properties then IDataErrorInfo is a very easy to use.I go through with most of the post but they not provide the combobox validation but here I explain the combobox validation also
First we need to create a class with some properties to test and list for binding the comboboxes

We create a class "Student" which inherit with IDataErrorInfo 
class Student : IDataErrorInfo
    {
        public string FirstName { get; set; }
        public int RollNumber { get; set; }
        public string Division { get; set; }

        public List<string> Divisions { get; set; }

        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get
            {
                string result = null;
                if (columnName == "FirstName")
                {
                    if (string.IsNullOrEmpty(FirstName) || FirstName.Length < 3)
                        result = "Please enter a Name";
                }
                if (columnName == "RollNumber")
                {
                    if (RollNumber <= 0)
                        result = "Please enter a Proper roll Number";
                }
                if (columnName == "Division")
                {
                    if (string.IsNullOrEmpty(Division))
                        result = "Please select Division";
                }
                return result;
            }
        }
    }


.xaml code

     <Window.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="Margin" Value="0,2,40,2" />
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">
                            <Border Background="OrangeRed" DockPanel.Dock="right" Margin="5,0,0,0" 
                                Width="20" Height="20" CornerRadius="5"
                                ToolTip="{Binding ElementName=customAdorner, 
                                          Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                                <TextBlock Text="?" VerticalAlignment="center" HorizontalAlignment="center" 
                                   FontWeight="Bold" Foreground="white" />
                            </Border>
                            <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
                                <Border BorderBrush="red" BorderThickness="1" />
                            </AdornedElementPlaceholder>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="Margin" Value="0,2,40,2" />
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">
                            <Border Background="OrangeRed" DockPanel.Dock="right" Margin="5,0,0,0" 
                                Width="20" Height="20" CornerRadius="5"
                                ToolTip="{Binding ElementName=customAdorner, 
                                          Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                                <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" 
                                   FontWeight="Bold" Foreground="white" />
                            </Border>
                            <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
                                <Border BorderBrush="red" BorderThickness="1" />
                            </AdornedElementPlaceholder>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid x:Name="grdStudentData" Margin="0,20">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>

        <Grid.CommandBindings>
            <CommandBinding Command="New" CanExecute="Confirm_CanExecute" Executed="Confirm_Executed" />
        </Grid.CommandBindings>

        <Label Content="First Name:" Grid.Column="0" Grid.Row="0" />
        <Label Content="Division:" Grid.Column="0" Grid.Row="1" />
        <Label Content="Roll No:" Grid.Column="0" Grid.Row="2" />
        
        <TextBox x:Name="txtFirstName" Grid.Row="0" Grid.Column="1" 
             Validation.Error="Validation_Error"
             Text="{Binding UpdateSourceTrigger=PropertyChanged, Path=FirstName,
                    ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />

        <ComboBox x:Name="cbpdepartment" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Divisions,Mode=TwoWay}" Validation.Error="Validation_Error" SelectedItem="{Binding UpdateSourceTrigger=PropertyChanged, Path=Division,ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />

        <TextBox x:Name="txtRollNumber" Grid.Row="2" Grid.Column="1" 
             Validation.Error="Validation_Error"
             Text="{Binding UpdateSourceTrigger=PropertyChanged, Path=RollNumber,
                    ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
        
        <Button Content="Submit" Grid.ColumnSpan="2" Grid.Row="3" Grid.Column="1" Margin="0,0,10,0"
            HorizontalAlignment="right" VerticalAlignment="Center" Command="New"/>
    </Grid>


.xaml.cs code


      private int _errors = 0;
        private Student _student = new Student();
        public ValidationPart1()
        {
            InitializeComponent();
            _student.Divisions = new List<string>();
            _student.Divisions.Add(string.Empty);
            _student.Divisions.Add("Fifth");
            _student.Divisions.Add("Sixth");
            _student.Divisions.Add("Seventh");
            grdStudentData.DataContext = _student;
        }

        private void Confirm_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _errors == 0;
            e.Handled = true;
        }

        private void Confirm_Executed(object sender, ExecutedRoutedEventArgs e)
        {
           //Insert logic of the page
        }

        private void Validation_Error(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errors++;
            else
                _errors--;
        }
        

Output
WPF Validation Example

WPF INTERVIEW QUESTIONS - MANOHAR GOUD 9866550012



Question :

What the first class that is loaded by any new WPF Application project?

Answer :

App. App.xaml and App.xaml.cs.

Question :

What is a DependencyProperty?

Answer :

Represents a property that can be set through methods such as, styling, data binding, animation, and inheritance.

Question :

What tool should you use sketch a mock of your WPF application?

Answer :

SketchFlow

Question :

What are common Localization/Globalization practices for Localizing/Globalizing WPF?

Answer :

1) Use Resources.resx
2) Use BAML
3) Use a ResourceDictionary to manage localizable strings.

Question :

What is the difference between X:name and x:key?

Answer :

X:name idetifies a UIElment in XAML Tree
X:Key identifies objects in resources section, can be accessed by resourceDictionary

Question :

What are the Resources, Styles and Triggers?

Answer :

Style - element containing setter elements.
Triggers - used to change the look and feel of the controls dynamically.
Resources - Styles and Triggers are stored in the resources
Static Resources - resources are searched at load time
Dynamic Resources - If the resource changes while the program is running

Question :

What is Property Invalidation?

Answer :

Its used to update the custom control whenever the property changes.Adding property invalidation callbacks to a custom control is as easy as adding a PropertyChangedCallback object to a PropertyMetadata object and add this PropertyMetadata object to Register() or RegisterAttached() methods.



Question :

What is the purpose of AccessText?

Answer :

AccessText enables you to specify displayed text with an embedded keyboard shortcut used to access the corresponding control. Simply precede the desired letter of the text with an underscore.

Question :

What are the types of Inlines that can be used in a TextBlock?

Answer :

Span
Bold
Italic
Underline
Hyperlink
Run
LineBreak
InlineUIContainer
Figure
Floater

Question :

What is the most common format for declaring a data binding in markup?

Answer :

Markup extensions are the most common means of declaring a data binding. They are identified by the use of curly brackets ({}).The less common format is XAML.

Question :

Is x:Static the same as a data binding?

Answer :

x:Static is another markup extension that is different from the data binding markup extension. It is used to retrieve data from static value members on classes.

Question :

How many ways are there to deploy WPF applications, and what are they?

Answer :

There are three ways to deploy WPF applications :
as a simple XAML file
an XBAP
or a standard executable.

Question :

How do navigation applications differ from standard WPF applications?

Answer :

Navigation applications are based on a web browser metaphor. They use pages instead of windows, and they include a forward and back button by default.

Question :

What type of elements can be hosted in a ToolBar?

Answer :

A ToolBar can host any type of .NET class.

Question :

What is the simplest and most common way to componentize a complex UI?

Answer :

The easiest way to break up a complex UI is to create separate UserControls for related parts and reference them from the original UI.

Question :

What class is used to save and load the content of a RichTextBox?

Answer :

To save or load the content of a RichTextBox, use the TextRange class.

Question :

What are the types of binding in WPF?

Answer :

There are two types of binding in WPF :
Key Binding
Mouse Binding

Question :

What is the difference between key binding and mouse binding?

Answer :

KeyBinding allows you to define gestures for commands that consist of a keystroke possibly combined with one or more modifiers, whereas MouseBinding allows you to define gestures for the mouse that can also be optionally combined with modifiers on the keyboard.

Question :

What type is used to render WPF output to a bitmap?

Answer :

Use RenderTargetBitmap to render WPF visuals to a bitmap.

Question :

What is the base class for all renderable types in WPF?

Answer :

All elements that are renderable must inherit from Visual.

Question :

What is a repository?

Answer :

A repository is a type of class that hides the actual data storage mechanism from the rest of the application.


Question :

What are the types sibling libraries in WPF?

Answer :

There are three types of sibling libraries of WPF are :
WCF
WF
CardSpace

Question :

What is the difference between WCF and WF?

Answer :

Windows Communication Foundation is focused on messaging. This API greatly simplifies all sorts of networking and communication tasks. It covers everything from web services to remoting to P2P and more.
A powerful library for building workflow enabled applications. It utilizes a markup language for declaring workflows in an application,and thus prevents workflow from becoming hard-coded. It also makes it very easy for developers to create custom workflow tasks.

Question :

What is XAML?

Answer :

XAML (pronounced as Zammel) is a declarative XML-based language by which you can define object and properties in XML. XAML document is loaded by a XAML parser. XAML parser instantiates objects and set there properties. XAML describes objects, properties and there relation in between them. Using XAML, you can create any kind of objects that means graphical or non-graphical.

Question :

What is the benefit of using a markup language for designing a user interface?

Answer :

Using a markup language such as XAML, or even HTML, is beneficial because it provides a common medium for both designers and developers. Additionally, the markup language allows for a declarative approach for building applications, which is often easier to construct and maintain.

Question :

What are the types of binding modes?

Answer :

There are three different binding modes :
one–way
two–way
one–way–to–source

Question :

What is the difference between a XAML file and a code-behind file?

Answer :

The XAML file contains the XAML markup, whereas the code-behind file is associated with a XAML file and contains code (such as C# or VB).

Question :

Which files are automatically added to a new WPF Application project?

Answer :

App.xaml and Window1.xaml, along with their associated code-behind files. The former represents the application as a whole, whereas the latter represents the primary window of the application.

Question :

What is the purpose of the x:Name attribute in XAML?

Answer :

The x:Name attribute allows you to uniquely identify an instance of an object defined in XAML. The value of the x:Name attribute can be referenced in the associated C# or VB code.

Question :

What is a feature of XAML that is available when it is compiled rather than interpreted?

Answer :

When your XAML is compiled, you can embed procedural code such as C# or VB. For more information about this, look up the markup extension x:Code.

Question :

What is an attached property?

Answer :

An attached property is a property that is declared by one control and attached to another. It allows the inclusion of additional information with a control for later use by an external source.

Question :

What kind of documents are supported in WPF?

Answer :

There are two kind of major document supported in
WPF Fixed format documents
Flow format document.

Question :

What is the difference between fixed format documents and flow format documents?

Answer :

Fixed format documents look like PDF format. They display content regardless of screen size and resolution. But Flow format document adjust depending on screen size and resolution.

Question :

What is the difference between a Panel and a Decorator?

Answer :

A Panel has a collection of Children that it arranges according to various rules, based on the type of panel.
A Decorator, on the other hand, has only one Child to which it applies some additional set of behavior.

Question :

What is the feature of silverlight 4?

Answer :

Silverlight 4 is the current version at the time of writing and it introduced a number of new features, including :
Support for Google’s Chrome web browser
Access to the user’s web cam and microphone
Mousewheel input
Enhancements to existing controls, such as the DataGrid
New controls, such as the RichTextBox
Enhanced data binding support
Managed Extensibility Framework support
WCF RIA services

Question :

What are the types of common file dialogs that WPF supports?

Answer :

The common file dialogs that WPF supports include SaveFileDialog, OpenFileDialog, and PrintDialog. WPF does not presently have a common dialog for folder selection, font selection, or print preview.

Question :

What is the name of the FrameworkElement most commonly used to work with media in WPF?

Answer :

MediaElement is used to play back a variety of audio and video formats.

Question :

What are two common properties on all the Shape classes?

Answer :

There are more than a dozen properties on the base class System.Windows.Shapes.Shape.
Fill
Stroke
StrokeDashArray
StrokeDashCap
StrokeEndLineCap
StrokeLineJoin
StrokeMiterLimit
StrokeStartLineCap
StrokeThickness

Question :

What are the different types of brushes that WPF offers?

Answer :

There are six different types of brushes
SolidColorBrush
LinearGradientBrush
RadialGradientBrush
DrawingBrush
VisualBrush
ImageBrush

Question :

What are the four channels of a WPF Color object?

Answer :

There are four channels of a WPF color objects are :
Alpha
Red
Green
Blue

Question :

What are the types of bitmap effects?

Answer :

The built-in bitmap effects are :
DropShadowBitmapEffect
OuterGlowBitmapEffect
BlurBitmapEffect
EmbossBitmapEffect
BevelBitmapEffect

Question :

What are the two types of transforms present on FrameworkElement?

Answer :

The two transforms that are present on FrameworkElement are RenderTransform and LayoutTransform.

Question :

What is Windows Workflow Foundation?

Answer :

WWF is a programming model for building workflow-enabled applications on windows. System.Workflow namespace has all the necessary modules to develop any type of workflow.

Question :

What is a Workflow?

Answer :

A Workflow is a set of activities, which is stored as model and they depict a process.Workflow is run by the Workflow runtime engine.

Question :

What Is ObservableCollection ?

Answer :

ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.

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



Properties
NameDescription
CountGets the number of elements actually contained in the Collection. (Inherited from Collection.)
ItemGets or sets the element at the specified index. (Inherited from Collection.)
ItemsGets a IList wrapper around the Collection. (Inherited from Collection.)


Methods
NameDescription
AddAdds an object to the end of the Collection. (Inherited from Collection.)
ClearRemoves all elements from the Collection. (Inherited from Collection.)
ClearItemsRemoves all items from the collection. (Overrides Collection.ClearItems().)
ContainsDetermines whether an element is in the Collection. (Inherited from Collection.)
InsertInserts an element into the Collection at the specified index. (Inherited from Collection.)
RemoveRemoves the first occurrence of a specific object from the Collection. (Inherited from Collection.)
RemoveAtRemoves the element at the specified index of the Collection. (Inherited from Collection.)
ToStringReturns a string that represents the current object. (Inherited from Object.)

Question :

What Is List ?

Answer :

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Arrays do not dynamically resize. The List type does. With List, you do not need to manage the size on your own. This type is ideal for linear collections not accessed by keys. It provides many methods and properties.



Properties
NameDescription
CapacityGets or sets the total number of elements the internal data structure can hold without resizing.
CountGets the number of elements actually contained in the List.
ItemGets or sets the element at the specified index.


Methods
NameDescription
AddAdds an object to the end of the List.
AddRangeAdds the elements of the specified collection to the end of the List.
AsReadOnlyReturns a read-only IList wrapper for the current collection.
ClearRemoves all elements from the List.
ContainsDetermines whether an element is in the List.
FindSearches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List.
FindAllRetrieves all the elements that match the conditions defined by the specified predicate.
ForEachPerforms the specified action on each element of the List.
IndexOf(T)Searches for the specified object and returns the zero-based index of the first occurrence within the entire List.
InsertInserts an element into the List at the specified index.
InsertRangeInserts the elements of a collection into the List at the specified index.
RemoveRemoves the first occurrence of a specific object from the List.
RemoveAllRemoves all the elements that match the conditions defined by the specified predicate.
RemoveAtRemoves the element at the specified index of the List.
RemoveRangeRemoves a range of elements from the List.
Sort()Sorts the elements in the entire List using the default comparer.
ToStringReturns a string that represents the current object. (Inherited from Object.)

Question :

What Is IEnumerable Collection ?

Answer :

Exposes an enumerator, which supports a simple iteration over a non-generic collection.



Methods
NameDescription
GetEnumeratorReturns an enumerator that iterates through a collection.


ObservableCollectionList
ObservableCollection is a generic dynamic data collection.It represents a strongly typed list of objects that can be accessed by index.
Its provides notifications (using an interface "INotifyCollectionChanged") when items get added, removed, or when the whole collection is refreshed.In the sample application, the values in the list are added, removed and changed during runtime in the code behind. The changes in the list will not be updated to the UI
Manupulation not allowed in ObservableCollectionA list provides methods to search, sort, and manipulate lists.

IEnumerableList
IEnumerable is an interfase, any class that subscribe to this needs to comply with it.List is a class that defines a generic collection
Enumerable describes behaviorList is an implementation of that behavior
IEnumerable is an interface - you can't create an IEnumerable, but rather must create some class that implements IEnumerable.List, on the other hand, is a concrete class. It implements IEnumerable directly.
IEnumerable basically only supports iterating over the results contained in the collectionList is more specific, and allows you to:
* Find out how many items are in the collection without iterating through all of them
* Easily access an item in a specific position in the list
* Add or remove items from the list
IEnumerable can move forward only over a collection, it can’t move backward and between the items.List is used to access an element in a specific position/index in a list.
IEnumerable doesn't support add or remove items from the list.List is useful when you want to Add or remove items from the list.
IEnumerable supports deferred execution.List supports deferred execution.
IEnumerable supports further filtering.List doesn't support further filtering.

IEnumerableObservableCollection
IEnumerable is simply an interface and any number of classes could be behind the actual implementation it.ObservableCollection is a generic dynamic data collection.
We don't really bind the IEnumerable, since that is an interface, but you are binding some collection/list that implements IEnumerable.ObservableCollection also implements IEnumerable so should be able to safely use that as the ItemSource instead.
IEnumerable is an interface - you can't create an IEnumerable, but rather must create some class that implements IEnumerable.ObservableCollection, on the other hand, is a concrete class. It implements IEnumerable directly.
IEnumerable basically only supports iterating over the results contained in the collectionObservableCollection is more specific, and allows you to:
* Find out how many items are in the collection without iterating through all of them
* Easily access an item in a specific position in the Collection
* Add or remove items from the Collection
IEnumerable can move forward only over a collection, it can’t move backward and between the items.ObservableCollection is used to access an element in a specific position/index in a list.
IEnumerable doesn't support add or remove items from the list.ObservableCollection is useful when you want to Add or remove items from the list.
IEnumerable supports deferred execution.ObservableCollection supports deferred execution.
IEnumerable supports further filtering.ObservableCollection doesn't support further filtering.



Friday, 25 October 2013

Data Binding in WPF - MANOHAR GOUD 9866550012



Data Binding in WPF

With WPF, you can perform data manipulation using Microsoft® .NET Framework code, XAML, or a combination of both. You can bind to controls, public properties, XML, or objects, making data binding quick, flexible, and easier than ever. So let's take a look at how you can get started binding your controls to the data sources of your choice.

Data Binding Specifics
To use WPF data binding, you must always have a target and a source. The target of the binding can be any accessible property or element that is derived from DependencyProperty—an example is a TextBox control's Text property. The source of the binding can be any public property, including properties of other controls, common language runtime (CLR) objects, XAML elements, ADO.NET DataSets, XML Fragments, and so forth. To help you get the binding right, WPF includes two special providers—the XmlDataProvider and the ObjectDataProvider.
Now let's take a look at how the WPF data-binding techniques work and I'll present practical examples that illustrate their use.

Creating a Simple Binding
Let's start with a simple example that illustrates how to bind a TextBlock's Text property to a ListBox's selected item. The code displayed in Figure 1 shows a ListBox that has six ListBoxItems declared. The second TextBlock in the code example has a property called Text (specified in XAML property-element syntax with the XML child element <TextBlock.Text>), which will contain the text for the TextBlock. The Text property declares a binding to the ListBox's selected item with the <Binding> tag. The ElementName attribute of the Binding tag indicates the name of the control that the TextBlock's Text property is bound to. The Path attribute indicates the property of the element (in this case the ListBox) that we will be binding to. The result of this code is that when a color is selected from the ListBox, the name of that color is shown in the TextBlock.
<StackPanel> <TextBlock Width="248" Height="24" Text="Colors:" TextWrapping="Wrap"/> <ListBox x:Name="lbColor" Width="248" Height="56"> <ListBoxItem Content="Blue"/> <ListBoxItem Content="Green"/> <ListBoxItem Content="Yellow"/> <ListBoxItem Content="Red"/> <ListBoxItem Content="Purple"/> <ListBoxItem Content="Orange"/> </ListBox> <TextBlock Width="248" Height="24" Text="You selected color:" /> <TextBlock Width="248" Height="24"> <TextBlock.Text> <Binding ElementName="lbColor" Path="SelectedItem.Content"/> </TextBlock.Text> </TextBlock> </StackPanel>
The code listed in Figure 1 can be modified slightly to use a shorthand syntax for data binding. For example, let's replace the TextBlock's <Binding> tag with the following code snippet:
<TextBlock Width="248" Height="24" Text="{Binding ElementName=lbColor, Path=SelectedItem.Content}" />
This syntax, called the attribute syntax, condenses the data binding code inside of the Text attribute of the TextBlock. Basically, the Binding tag gets pulled inside of the curly braces along with its attributes.

Binding Modes
I can take the previous example further, binding the background color of the TextBlock to the color that is selected in the ListBox. The following code adds a Background property to the TextBlock and uses the attribute binding syntax to bind to the value of the selected item in the ListBox:
<TextBlock Width="248" Height="24" Text="{Binding ElementName=lbColor, Path=SelectedItem.Content, Mode=OneWay}" x:Name="tbSelectedColor" Background="{Binding ElementName=lbColor, Path=SelectedItem.Content, Mode=OneWay}"/>
When the user selects a color in the ListBox, the name of that color will appear in the TextBlock and the background color of the TextBlock will change to the selected color (see Figure 2).
Figure 2 Binding a Source to Two Targets 
Notice the statement in the previous example that sets the Mode attribute to OneWay. The Mode attribute defines the binding mode that will determine how data flows between the source and the target. In addition to OneWay, there are three other binding modes available: OneTime, OneWayToSource, and TwoWay,
When using OneWay binding, as shown in the preceding code snippet, the data flows from the source to the target each time a change is made on the source. And while I explicitly specified this binding mode in my example, OneWay binding is the default binding mode for the TextBlock's Text property and does not need to be specified. Like OneWay binding, OneTime binding sends data from the source to the target; however, it does this only when the application is started or when the DataContext changes and, as a result, does not listen for change notifications in the source. Unlike OneWay and OneTime binding, OneWayToSource binding sends data from the target to the source. Finally, TwoWay binding sends the source data to the target, and if there are changes in the target property's value, those will be sent back to the source.
In the previous example, I used OneWay binding because I wanted the source (the selected ListBoxItem) to be sent to the TextBlock whenever a change is made in the ListBox selection. I do not want changes from the TextBlock to go back to the ListBox. Of course, there is no way for a user to edit a TextBlock. If I want to explore TwoWay binding, I can add a TextBox to this code, bind its text and background color to the ListBox, and set the Mode to TwoWay. When a user selects a color in the ListBox, the color is shown in the TextBox and its background color changes. When that user types in a color (such as Cyan) in the TextBox, the name of the color is updated in the ListBox (target to source) and in turn, since the ListBox was updated, the new value is sent to all elements that are bound to the ListBox's SelectedItem property. This means that the TextBlock will also have its color updated and its text value set to the new color (seeFigure 3).
Figure 3 TwoWay Binding in Action 
Here's the code I used to bind the TextBlock (OneWay) and the TextBox (TwoWay) to the ListBox:
<TextBlock Width="248" Height="24" Text="{Binding ElementName=lbColor, Path=SelectedItem.Content, Mode=OneWay}" x:Name="tbSelectedColor" Background="{Binding ElementName=lbColor, Path=SelectedItem.Content, Mode=OneWay}"/> <TextBox Width="248" Height="24" Text="{Binding ElementName=lbColor, Path=SelectedItem.Content, Mode=TwoWay}" x:Name="txtSelectedColor" Background="{Binding ElementName=lbColor, Path=SelectedItem.Content, Mode=OneWay}"/>
If I change the TwoWay mode back to OneWay, the user will be able to edit the color in the TextBox without causing the changed value to be sent back to the ListBox.
Selecting the appropriate binding mode is important. I often employ OneWay when I want to display read-only data to a user. I use TwoWay binding when I want the user to be able to change the data in the control and have that change reflected in the data source (a DataSet, object, XML, or another bound control). I find OneWayToSource to be a good choice when I want to allow a user to change the data source without having the data source bind its data back to the target. I have used OneTime binding when I was tasked with showing, in a read-only control, the state of the data as it was when the screen loaded. Using OneTime binding, a series of read-only controls was bound to the data and, as the user interacted with the form and the data source's values were changed, the bound controls remained unchanged. This provided a way for the users to compare the changes that were made. Additionally, OneTime binding is a good choice when your source doesn't implement INotifyPropertyChanged.

A Time to Bind
In the previous example, the TextBox allows TwoWay binding to the selected ListBoxItem in the ListBox. This flow of data from the TextBox back to the ListBox happens when the TextBox loses focus. To change the event that causes the data to be sent back to the source, you can specify a value for UpdateSourceTrigger, which is the binding property that defines when the source should be updated. There are three values that can be set for the UpdateSourceTrigger: Explicit, LostFocus, and PropertyChanged.
When you set the UpdateSourceTrigger to Explicit, the source will not be updated unless the BindingExpression.UpdateSource method is called from code. The LostFocus setting (the default value for the TextBox control) indicates that the source will be updated when the target control loses focus. The PropertyChanged value indicates that the target will update the source every time the target control's bound property changes. This setting is useful when you want to dictate when the binding will occur.

Binding to XML
Binding to data sources such as XML and objects is also handy. Figure 4 shows a sample of an XmlDataProvider that contains an embedded list of colors that will be used as a data source. The XmlDataProvider can be used to bind to an XML document or fragment that is either embedded in the XmlDataProvider tag or is in a file referred to in an external location.
<StackPanel> <StackPanel.Resources> <XmlDataProvider x:Key="MoreColors" XPath="/colors"> <x:XData> <colors > <color name="pink"/> <color name="white"/> <color name="black"/> <color name="cyan"/> <color name="gray"/> <color name="magenta"/> </colors> </x:XData> </XmlDataProvider>
Embedded XML content must be placed within a <x:XData> tag inside of an XmlDataProvider, as shown in Figure 4. The XmlDataProvider must be given an x:Key value so that it can be referred to by data-binding targets. Notice that the XPath attribute is set to "/colors". This attribute defines the level of the XML content that will be used as the data source. This becomes very useful when binding to a large XML structure that may be contained in a file or database and the data you want to bind to is not the root element.
An XmlDataProvider is a resource that can be placed inside of a context-specific resource. As Figure 4shows, the XmlDataProvider is defined as a resource within the context of the StackPanel. This means that the XmlDataProvider will be available to all content inside of that StackPanel. Setting the context of a resource helps limit the exposure of a data source to the appropriate areas. This enables you to create well-defined, self-contained regions of both controls and supporting resources within your page, thus improving readability.
The syntax for binding to a resource is slightly different than it is for binding to an element. When binding to a control, you set the ElementName and the Path properties of the Binding. However, when you bind to a resource you set the Source and, since we are binding to an XmlDataProvider, you set the XPath property of the Binding as well. For example, the following code will bind the ListBox's items to the MoreColors resource. The Source property is set to a resource and it is specified as a StaticResource named MoreColors. The XPath property indicates that the items will be bound to the <color> element's name attribute within the XML data source:
<ListBox x:Name="lbColor" Width="248" Height="56" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource MoreColors}, XPath=color/@name}"> </ListBox>
I specified StaticResource in this case because the XML will not change. If changes occur in the data source, they will not be sent to the target. The DynamicResource setting indicates the opposite—changes will be sent. This is useful when referencing system themes, languages in globalization, or fonts. A DynamicResource will allow these types of settings to be propagated throughout the UI elements that are bound to them dynamically.
The XmlDataProvider can also point to an external source for the XML content. For my example, I have a file named colors.xml that contains the list of colors I want my ListBox to be bound to. I can simply add a second XmlDataProvider resource to the StackPanel and direct it to the XML file. Notice I set the Source attribute to the name of the XML file and the x:Key to Colors:
<XmlDataProvider x:Key="Colors" Source="Colors.xml" XPath="/colors"/>
Both XmlDataProviders exist as resources within the same StackPanel. I can tell the ListBox to bind itself to this new resource by changing the name that the StaticResource is set to:
<ListBox x:Name="lbColor" Width="248" Height="56" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource Colors}, XPath=color/@name}"> </ListBox>

Object Binding and DataTemplates
While the XmlDataProvider works great for XML, when you want to bind to an object or a list of objects, you can create an ObjectDataProvider as a resource. The ObjectDataProvider's ObjectType designates the object that will provide the data‑binding source while the MethodName indicates the method that will be invoked to get the data. For example, assuming I have a class called PersonService that has a method called GetPersonList that returns a List<Person>, the ObjectDataProvider would look like this:
<StackPanel.Resources> <ObjectDataProvider x:Key="persons" ObjectType="{x:Type svc:PersonService}" MethodName="GetPersonList"></ObjectDataProvider> </StackPanel.Resources>
If you want a more complete look, the PersonService and Person classes, as well as all other sample code, are contained in the code that accompanies this column.
There are a handful of other properties that are available on the ObjectDataProvider. The ConstructionParameters property allows you to pass parameters to the constructor of the class being invoked. You can also specify parameters using the MethodParameters property, and you can use the ObjectInstance property to specify an existing instance of an object as the source.
If you want the data to be retrieved asynchronously, you can set the IsAsynchronous property of the ObjectDataProvider to true. Then the user will be able to interact with the screen while waiting for the data to populate in the target control that is bound to the ObjectDataProvider's source.
When adding an ObjectDataProvider, you have to qualify the namespace of the data-source class. In this case, I have to add an xmlns attribute to the <Window> tag so that the svc shortcut is qualified and indicates the proper namespace:
xmlns:svc="clr-namespace:DataBindingWPF"
Now that the data source is defined via the ObjectDataProvider, I want to bind items in a ListBox control to this data. I want to display two lines of text in each ListBoxItem. The first line will display the FullName property of the Person instance in bold and the second line will show the Title and City of the instance. In XAML, this is quite simple using DataTemplates, which allow you to define a data visualization strategy that can be reused.
Figure 5 shows the completed XAML, which has a DataTemplate defined to display the Person information in the layout I designated. I set the DataType property of the DataTemplate to indicate that the DataTemplate will be referring to the Person class type. I do not specify the actual binding in the DataTemplate, as I will do this in the ListBox control. By omitting the Binding Source, the binding will be made to the current DataContext in scope.
In Figure 5, I set the ListBox's ItemsSource property to bind to the persons resource so that I could bind the data to the ListBox but not format it. The data is correctly displayed by setting the ItemTemplate property to the personLayout resource, which is the DataTemplate's key name. The ultimate result is a screen that looks like Figure 6.
<Window x:Class="DataBindingWPF.ObjectBinding" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:svc="clr-namespace:DataBindingWPF" Title="DataBindingWPF" Height="300" Width="300"> <StackPanel> <StackPanel.Resources> <ObjectDataProvider x:Key="persons" ObjectType="{x:Type svc:PersonService}" MethodName="GetPersonList" ></ObjectDataProvider> <DataTemplate x:Key="personLayout" DataType="Person"> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Path=FullName}" FontWeight="Bold" Foreground="Blue"> </TextBlock> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=Title}"></TextBlock> <TextBlock Text=", "></TextBlock> <TextBlock Text="{Binding Path=City}"></TextBlock> </StackPanel> </StackPanel> </DataTemplate> </StackPanel.Resources> <TextBlock></TextBlock> <ListBox x:Name="lbPersons" ItemsSource="{Binding Source={StaticResource persons}}" ItemTemplate="{DynamicResource personLayout}" IsSynchronizedWithCurrentItem="True"/> </StackPanel> </Window>
Figure 6 Using a DataTemplate 

Sorting the Data
If you want to sort your data in a specific way, you can bind to a CollectionViewSource instead of directly to the ObjectDataProvider. The CollectionViewSource then becomes the data source and serves as an intermediary that intercepts the data from the ObjectDataProvider; provides sorting, grouping, and filtering functionality; and then propagates it to the target.
The CollectionViewSource shown next has its Source attribute set to the resource name of the ObjectDataProvider (persons). I then defined a sort order for the data by indicating the properties to sort by and their direction:
<CollectionViewSource x:Key="personView" Source="{Binding Source={StaticResource persons}}"> <CollectionViewSource.SortDescriptions> <ComponentModel:SortDescription PropertyName="City" Direction="Ascending" /> <ComponentModel:SortDescription PropertyName="FullName" Direction="Descending" /> </CollectionViewSource.SortDescriptions> </CollectionViewSource>
The DataContext is used to bind all controls within a container control to a data source. This is very useful when you have several controls that all use the same binding source. The code could get repetitive if you indicated the binding source for every control. Instead, you can set the DataContext for the container of the controls to the binding source and simply omit the Source attribute from the contained controls. For example, here is a series of TextBlocks bound explicitly to the same binding source:
<StackPanel> <TextBlock Text="{Binding Source={StaticResource personView}, Path=FullName}"></TextBlock> <TextBlock Text="{Binding Source={StaticResource personView}, Path=Title}"></TextBlock> <TextBlock Text="{Binding Source={StaticResource personView}, Path=City}"></TextBlock> </StackPanel>
Here are the same three TextBoxes bound to the DataContext, which refers back to the controls' StackPanel container:
<StackPanel DataContext="{Binding Source={StaticResource personView}}" > <TextBlock Text="{Binding Path=FullName}"></TextBlock> <TextBlock Text="{Binding Path=Title}"></TextBlock> <TextBlock Text="{Binding Path=City}"></TextBlock> </StackPanel>
If the container does not define a DataContext, then it will continue to look at the next outer nested container until it finds the current DataContext.

Forging Ahead
WPF data binding offers a great deal of flexibility and control over the type of data that can be bound to, and how it can be controlled and displayed. With so much power and so many choices, I'm sure you'll want to get your hands dirty right away.