Dotnet Desktop WPF Data
Dotnet Desktop WPF Data
Data binding in Windows Presentation Foundation (WPF) provides a simple and consistent way
for apps to present and interact with data. Elements can be bound to data from different kinds
of data sources in the form of .NET objects and XML. Any ContentControl such as Button and
any ItemsControl, such as ListBox and ListView, have built-in functionality to enable flexible
styling of single data items or collections of data items. Sort, filter, and group views can be
generated on top of the data.
The data binding in WPF has several advantages over traditional models, including inherent
support for data binding by a broad range of properties, flexible UI representation of data, and
clean separation of business logic from UI.
This article first discusses concepts fundamental to WPF data binding and then covers the
usage of the Binding class and other features of data binding.
A typical use of data binding is to place server or local configuration data into forms or other
UI controls. In WPF, this concept is expanded to include binding a broad range of properties to
different kinds of data sources. In WPF, dependency properties of elements can be bound to
.NET objects (including ADO.NET objects or objects associated with Web Services and Web
properties) and XML data.
For example, if you bound the content of a TextBox to the Employee.Name property, you
would set up your binding like the following table:
ノ Expand table
Setting Value
Target TextBox
Most UIElement properties are dependency properties, and most dependency properties,
except read-only ones, support data binding by default. Only types derived from
DependencyObject can define dependency properties. All UIElement types derive from
DependencyObject .
Although not shown in the figure, it should be noted that the binding source object isn't
restricted to being a custom .NET object. WPF data binding supports data in the form of
.NET objects, XML, and even XAML element objects. To provide some examples, your
binding source may be a UIElement, any list object, an ADO.NET or Web Services object,
or an XmlNode that contains your XML data. For more information, see Binding sources
overview.
It's important to remember that when you're establishing a binding, you're binding a binding
target to a binding source. For example, if you're displaying some underlying XML data in a
ListBox using data binding, you're binding your ListBox to the XML data.
To establish a binding, you use the Binding object. The rest of this article discusses many of the
concepts associated with and some of the properties and usage of the Binding object.
Data context
When data binding is declared on XAML elements, they resolve data binding by looking at
their immediate DataContext property. The data context is typically the binding source object
for the binding source value path evaluation. You can override this behavior in the binding and
set a specific binding source object value. If the DataContext property for the object hosting
the binding isn't set, the parent element's DataContext property is checked, and so on, up until
the root of the XAML object tree. In short, the data context used to resolve binding is inherited
from the parent unless explicitly set on the object.
Bindings can be configured to resolve with a specific object, as opposed to using the data
context for binding resolution. Specifying a source object directly is used when, for example,
you bind the foreground color of an object to the background color of another object. Data
context isn't needed since the binding is resolved between those two objects. Inversely,
bindings that aren't bound to specific source objects use data-context resolution.
When the DataContext property changes, all bindings that could be affected by the data
context are reevaluated.
You may want your app to enable users to change the data and propagate it back to the
source object. Or you may not want to enable users to update the source data. You can control
the flow of data by setting the Binding.Mode.
This figure illustrates the different types of data flow:
OneWay binding causes changes to the source property to automatically update the
target property, but changes to the target property are not propagated back to the
source property. 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's no need to monitor the changes
of the target property, using the OneWay binding mode avoids the overhead of the
TwoWay binding mode.
TwoWay binding causes changes to either the source property or the target property to
automatically update the other. 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
TextBox.Text and CheckBox.IsChecked default to TwoWay binding.
C#
/* Displays:
*
* TextBox.Text property metadata:
* BindsTwoWayByDefault: True
* IsDataBindingAllowed: True
* AffectsArrange: False
* AffectsMeasure: False
* AffectsRender: False
* Inherits: False
*/
}
OneWayToSource is the reverse of OneWay binding; it updates the source property when
the target property changes. One example scenario is if you only need to reevaluate the
source value from the UI.
Not illustrated in the figure is OneTime binding, which causes the source property to
initialize the target property but doesn't propagate subsequent changes. If the data
context changes or the object in the data context changes, the change is not reflected in
the target property. This type of binding is appropriate if either a snapshot of the current
state is appropriate 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 isn't known in advance. This mode is essentially a simpler form of OneWay
binding that provides better performance in cases where the source value doesn't
change.
To detect source changes (applicable to OneWay and TwoWay bindings), the source must
implement a suitable property change notification mechanism such as
INotifyPropertyChanged. See How to: Implement property change notification (.NET
Framework) for an example of an INotifyPropertyChanged implementation.
The Binding.Mode property provides more information about binding modes and an example
of how to specify the direction of a binding.
What triggers source updates
Bindings that are TwoWay or OneWayToSource listen for changes in the target property and
propagate them back to the source, known as updating the source. For example, you may edit
the text of a TextBox to change the underlying source value.
However, is your source value updated while you're editing the text or after you finish editing
the text and the control loses focus? The Binding.UpdateSourceTrigger property determines
what triggers the update of the source. The dots of the right arrows in the following figure
illustrate the role of the Binding.UpdateSourceTrigger property.
Similar to the Mode property, different dependency properties have different default
UpdateSourceTrigger values. The default value for most dependency properties is
PropertyChanged, which causes the source property's value to instantly change when the
target property value is changed. Instant changes are fine for CheckBox and other simple
controls. However, for text fields, updating after every keystroke can diminish performance and
denies the user the usual opportunity to backspace and fix typing errors before committing to
the new value. For example, the TextBox.Text property defaults to the UpdateSourceTrigger
value of LostFocus, which causes the source value to change only when the control element
loses focus, not when the TextBox.Text property is changed. See the UpdateSourceTrigger
property page for information about how to find the default value of a dependency property.
The following table provides an example scenario for each UpdateSourceTrigger value using
the TextBox as an example.
ノ Expand table
UpdateSourceTrigger When the source Example scenario for TextBox
value value is updated
LostFocus (default for When the TextBox A TextBox that is associated with validation logic
TextBox.Text) control loses focus. (see Data Validation below).
PropertyChanged As you type into the TextBox controls in a chat room window.
TextBox.
Explicit When the app calls TextBox controls in an editable form (updates the
UpdateSource. source values only when the user presses the
submit button).
For an example, see How to: Control when the TextBox text updates the source (.NET
Framework).
The data (AuctionItem objects) displayed in the ListBox is templated so that the
description and the current price are shown for each item. The template is created by
using a DataTemplate. In addition, the appearance of each item depends on the
SpecialFeatures value of the AuctionItem being displayed. If the SpecialFeatures value of
the AuctionItem is Color, the item has a blue border. If the value is Highlight, the item has
an orange border and a star. The Data Templating section provides information about
data templating.
The user can group, filter, or sort the data using the CheckBoxes provided. In the image
above, the Group by category and Sort by category and date CheckBoxes are selected.
You may have noticed that the data is grouped based on the category of the product, and
the category name is in alphabetical order. It's difficult to notice from the image but the
items are also sorted by the start date within each category. Sorting is done using a
collection view. The Binding to collections section discusses collection views.
When the user selects an item, the ContentControl displays the details of the selected
item. This experience is called the Master-detail scenario. The Master-detail scenario
section provides information about this type of binding.
The type of the StartDate property is DateTime, which returns a date that includes the
time to the millisecond. In this app, a custom converter has been used so that a shorter
date string is displayed. The Data conversion section provides information about
converters.
When the user selects the Add Product button, the following form comes up.
The user can edit the fields in the form, preview the product listing using the short or detailed
preview panes, and select Submit to add the new product listing. Any existing grouping,
filtering and sorting settings will apply to the new entry. In this particular case, the item entered
in the above image will be displayed as the second item within the Computer category.
Not shown in this image is the validation logic provided in the Start Date TextBox. If the user
enters an invalid date (invalid formatting or a past date), the user will be notified with a ToolTip
and a red exclamation point next to the TextBox. The Data Validation section discusses how to
create validation logic.
Before going into the different features of data binding outlined above, we will first discuss the
fundamental concepts that are critical to understanding WPF data binding.
Create a binding
To restate some of the concepts discussed in the previous sections, you establish a binding
using the Binding object, and each binding usually has four components: a binding target, a
target property, a binding source, and a path to the source value to use. This section discusses
how to set up a binding.
Binding sources are tied to the active DataContext for the element. Elements automatically
inherit their DataContext if they've not explicitly defined one.
Consider the following example, in which the binding source object is a class named MyData
that is defined in the SDKSample namespace. For demonstration purposes, MyData has a string
property named ColorName whose value is set to "Red". Thus, this example generates a button
with a red background.
XAML
<DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample">
<DockPanel.Resources>
<c:MyData x:Key="myDataSource"/>
</DockPanel.Resources>
<DockPanel.DataContext>
<Binding Source="{StaticResource myDataSource}"/>
</DockPanel.DataContext>
<Button Background="{Binding Path=ColorName}"
Width="150" Height="30">
I am bound to be RED!
</Button>
</DockPanel>
For more information on the binding declaration syntax and examples of how to set up a
binding in code, see Binding declarations overview.
If we apply this example to our basic diagram, the resulting figure looks like the following. This
figure describes a OneWay binding because the Background property supports OneWay
binding by default.
You may wonder why this binding works even though the ColorName property is of type string
while the Background property is of type Brush. This binding uses default type conversion,
which is discussed in the Data conversion section.
There are several ways to specify the binding source object. Using the DataContext property on
a parent element is useful when you're binding multiple properties to the same source.
However, sometimes it may be more appropriate to specify the binding source on individual
binding declarations. For the previous example, instead of using the DataContext property, you
can specify the binding source by setting the Binding.Source property directly on the binding
declaration of the button, as in the following example.
XAML
<DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample">
<DockPanel.Resources>
<c:MyData x:Key="myDataSource"/>
</DockPanel.Resources>
<Button Background="{Binding Source={StaticResource myDataSource},
Path=ColorName}"
Width="150" Height="30">
I am bound to be RED!
</Button>
</DockPanel>
Other than setting the DataContext property on an element directly, inheriting the DataContext
value from an ancestor (such as the button in the first example), and explicitly specifying the
binding source by setting the Binding.Source property on the binding (such as the button the
last example), you can also use the Binding.ElementName property or the
Binding.RelativeSource property to specify the binding source. The ElementName property is
useful when you're binding to other elements in your app, such as when you're using a slider
to adjust the width of a button. The RelativeSource property is useful when the binding is
specified in a ControlTemplate or a Style. For more information, see Binding sources overview.
Although we have emphasized that the Path to the value to use is one of the four necessary
components of a binding, in the scenarios that you want to bind to an entire object, the value
to use would be the same as the binding source object. In those cases, it's applicable to not
specify a Path. Consider the following example.
XAML
<ListBox ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="true"/>
The above example uses the empty binding syntax: {Binding}. In this case, the ListBox inherits
the DataContext from a parent DockPanel element (not shown in this example). When the path
isn't specified, the default is to bind to the entire object. In other words, in this example, the
path has been left out because we are binding the ItemsSource property to the entire object.
(See the Binding to collections section for an in-depth discussion.)
Other than binding to a collection, this scenario is also useful when you want to bind to an
entire object instead of just a single property of an object. For example, if your source object is
of type String, you may simply want to bind to the string itself. Another common scenario is
when you want to bind an element to an object with several properties.
You may need to apply custom logic so that the data is meaningful to your bound target
property. The custom logic may be in the form of a custom converter if default type conversion
doesn't exist. See Data conversion for information about converters.
Binding and BindingExpression
Before getting into other features and usages of data binding, it's useful to introduce the
BindingExpression class. As you have seen in previous sections, the Binding class is the high-
level class for the declaration of a binding; it provides many properties that allow you to specify
the characteristics of a binding. A related class, BindingExpression, is the underlying object that
maintains the connection between the source and the target. A binding contains all the
information that can be shared across several binding expressions. A BindingExpression is an
instance expression that cannot be shared and contains all the instance information of the
Binding.
Consider the following example, where myDataObject is an instance of the MyData class,
myBinding is the source Binding object, and MyData is a defined class that contains a string
property named ColorName . This example binds the text content of myText , an instance of
TextBlock, to ColorName .
C#
// Bind the data source to the TextBox control's Text dependency property
myText.SetBinding(TextBlock.TextProperty, myBinding);
You can use the same myBinding object to create other bindings. For example, you can use the
myBinding object to bind the text content of a check box to ColorName. In that scenario, there
will be two instances of BindingExpression sharing the myBinding object.
Get the binding object from a bound target property (.NET Framework)
Control When the TextBox text updates the source (.NET Framework)
Data conversion
In the Create a binding section, the button is red because its Background property is bound to
a string property with the value "Red". This string value works because a type converter is
present on the Brush type to convert the string value to a Brush.
Adding this information to the figure in the Create a binding section looks like this.
However, what if instead of having a property of type string your binding source object has a
Color property of type Color? In that case, in order for the binding to work you would need to
first turn the Color property value into something that the Background property accepts. You
would need to create a custom converter by implementing the IValueConverter interface, as in
the following example.
C#
[ValueConversion(typeof(Color), typeof(SolidColorBrush))]
public class ColorBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Color color = (Color)value;
return new SolidColorBrush(color);
}
Now the custom converter is used instead of default conversion, and our diagram looks like
this.
To reiterate, default conversions may be available because of type converters that are present
in the type being bound to. This behavior will depend on which type converters are available in
the target. If in doubt, create your own converter.
The following are some typical scenarios where it makes sense to implement a data converter:
Your data should be displayed differently, depending on culture. For instance, you might
want to implement a currency converter or a calendar date/time converter based on the
conventions used in a particular culture.
The data being used isn't necessarily intended to change the text value of a property, but
is instead intended to change some other value, such as the source for an image, or the
color or style of the display text. Converters can be used in this instance by converting the
binding of a property that might not seem to be appropriate, such as binding a text field
to the Background property of a table cell.
More than one control or multiple properties of controls are bound to the same data. In
this case, the primary binding might just display the text, whereas other bindings handle
specific display issues but still use the same binding as source information.
Binding to collections
A binding source object can be treated either as a single object whose properties contain data
or as a data collection of polymorphic objects that are often grouped together (such as the
result of a query to a database). So far we've only discussed binding to single objects. However,
binding to a data collection is a common scenario. For example, a common scenario is to use
an ItemsControl such as a ListBox, ListView, or TreeView to display a data collection, such as in
the app shown in the What is data binding section.
Fortunately, our basic diagram still applies. If you're binding an ItemsControl to a collection,
the diagram looks like this.
Collection views
Once your ItemsControl is bound to a data collection, you may want to sort, filter, or group the
data. To do that, you use collection views, which are classes that implement the ICollectionView
interface.
What Are collection views?
A collection view is a layer on top of a binding source collection that allows you to navigate
and display the source collection based on sort, filter, and group queries, without having to
change the underlying source collection itself. A collection view also maintains a pointer to the
current item in the collection. If the source collection implements the INotifyCollectionChanged
interface, the changes raised by the CollectionChanged event are propagated to the views.
Because views do not change the underlying source collections, each source collection can
have multiple views associated with it. For example, you may have a collection of Task objects.
With the use of views, you can display that same data in different ways. For example, on the left
side of your page you may want to show tasks sorted by priority, and on the right side,
grouped by area.
One way to create and use a view is to instantiate the view object directly and then use it as the
binding source. For example, consider the Data binding demo app shown in the What is data
binding section. The app is implemented such that the ListBox binds to a view over the data
collection instead of the data collection directly. The following example is extracted from the
Data binding demo app. The CollectionViewSource class is the XAML proxy of a class that
inherits from CollectionView. In this particular example, the Source of the view is bound to the
AuctionItems collection (of type ObservableCollection<T>) of the current app object.
XAML
<Window.Resources>
<CollectionViewSource
Source="{Binding Source={x:Static Application.Current}, Path=AuctionItems}"
x:Key="listingDataView" />
</Window.Resources>
The resource listingDataView then serves as the binding source for elements in the app, such
as the ListBox.
XAML
To create another view for the same collection, you can create another CollectionViewSource
instance and give it a different x:Key name.
The following table shows what view data types are created as the default collection view or by
CollectionViewSource based on the source collection type.
ノ Expand table
IBindingList BindingListCollectionView
To get the default view, you use the GetDefaultView method. For an example, see Get the
default view of a data collection (.NET Framework).
Sorting
As mentioned before, views can apply a sort order to a collection. As it exists in the underlying
collection, your data may or may not have a relevant, inherent order. The view over the
collection allows you to impose an order, or change the default order, based on comparison
criteria that you supply. Because it's a client-based view of the data, a common scenario is that
the user might want to sort columns of tabular data per the value that the column corresponds
to. Using views, this user-driven sort can be applied, again without making any changes to the
underlying collection or even having to requery for the collection content. For an example, see
Sort a GridView column when a header is clicked (.NET Framework).
The following example shows the sorting logic of the "Sort by category and date" CheckBox of
the app UI in the What is data binding section.
C#
Filtering
Views can also apply a filter to a collection, so that the view shows only a certain subset of the
full collection. You might filter on a condition in the data. For instance, as is done by the app in
the What is data binding section, the "Show only bargains" CheckBox contains logic to filter
out items that cost $25 or more. The following code is executed to set ShowOnlyBargainsFilter
as the Filter event handler when that CheckBox is selected.
C#
C#
Grouping
Except for the internal class that views an IEnumerable collection, all collection views support
grouping, which allows the user to partition the collection in the collection view into logical
groups. The groups can be explicit, where the user supplies a list of groups, or implicit, where
the groups are generated dynamically depending on the data.
The following example shows the logic of the "Group by category" CheckBox.
C#
For another grouping example, see Group Items in a ListView That Implements a GridView
(.NET Framework).
Views also support the notion of a current item. You can navigate through the objects in a
collection view. As you navigate, you're moving an item pointer that allows you to retrieve the
object that exists at that particular location in the collection. For an example, see Navigate
through the objects in a data CollectionView (.NET Framework).
Because WPF binds to a collection only by using a view (either a view you specify, or the
collection's default view), all bindings to collections have a current item pointer. When binding
to a view, the slash ("/") character in a Path value designates the current item of the view. In
the following example, the data context is a collection view. The first line binds to the
collection. The second line binds to the current item in the collection. The third line binds to
the Description property of the current item in the collection.
XAML
XAML
The current item pointer can be affected by any sorting or filtering that is applied to the
collection. Sorting preserves the current item pointer on the last item selected, but the
collection view is now restructured around it. (Perhaps the selected item was at the beginning
of the list before, but now the selected item might be somewhere in the middle.) Filtering
preserves the selected item if that selection remains in view after the filtering. Otherwise, the
current item pointer is set to the first item of the filtered collection view.
The notion of a current item is useful not only for navigation of items in a collection, but also
for the master-detail binding scenario. Consider the app UI in the What is data binding section
again. In that app, the selection within the ListBox determines the content shown in the
ContentControl. To put it in another way, when a ListBox item is selected, the ContentControl
shows the details of the selected item.
You can implement the master-detail scenario simply by having two or more controls bound to
the same view. The following example from the Data binding demo shows the markup of the
ListBox and the ContentControl you see on the app UI in the What is data binding section.
XAML
Notice that both of the controls are bound to the same source, the listingDataView static
resource (see the definition of this resource in the How to create a view section). This binding
works because when an object (the ContentControl in this case) is bound to a collection view, it
automatically binds to the CurrentItem of the view. The CollectionViewSource objects
automatically synchronize currency and selection. If your list control isn't bound to a
CollectionViewSource object as in this example, then you would need to set its
IsSynchronizedWithCurrentItem property to true for this to work.
For other examples, see Bind to a collection and display information based on selection (.NET
Framework) and Use the master-detail pattern with hierarchical data (.NET Framework).
You may have noticed that the above example uses a template. In fact, the data would not be
displayed the way we wish without the use of templates (the one explicitly used by the
ContentControl and the one implicitly used by the ListBox). We now turn to data templating in
the next section.
Data templating
Without the use of data templates, our app UI in the Example of data binding section would
look like the following:
As shown in the example in the previous section, both the ListBox control and the
ContentControl are bound to the entire collection object (or more specifically, the view over
the collection object) of AuctionItems. Without specific instructions of how to display the data
collection, the ListBox displays the string representation of each object in the underlying
collection, and the ContentControl displays the string representation of the object it's bound
to.
To solve that problem, the app defines DataTemplates. As shown in the example in the previous
section, the ContentControl explicitly uses the detailsProductListingTemplate data template. The
ListBox control implicitly uses the following data template when displaying the AuctionItem
objects in the collection.
XAML
With the use of those two DataTemplates, the resulting UI is the one shown in the What is data
binding section. As you can see from that screenshot, in addition to letting you place data in
your controls, DataTemplates allow you to define compelling visuals for your data. For example,
DataTriggers are used in the above DataTemplate so that AuctionItems with SpecialFeatures
value of HighLight would be displayed with an orange border and a star.
For more information about data templates, see the Data templating overview (.NET
Framework).
Data validation
Most app that take user input need to have validation logic to ensure that the user has entered
the expected information. The validation checks can be based on type, range, format, or other
app-specific requirements. This section discusses how data validation works in WPF.
XAML
A ValidationRule object checks whether the value of a property is valid. WPF has two types of
built-in ValidationRule objects:
A ExceptionValidationRule checks for exceptions thrown during the update of the binding
source property. In the previous example, StartPrice is of type integer. When the user
enters a value that cannot be converted to an integer, an exception is thrown, causing the
binding to be marked as invalid. An alternative syntax to setting the
ExceptionValidationRule explicitly is to set the ValidatesOnExceptions property to true on
your Binding or MultiBinding object.
A DataErrorValidationRule object checks for errors that are raised by objects that
implement the IDataErrorInfo interface. For more information about using this validation
rule, see DataErrorValidationRule. An alternative syntax to setting the
DataErrorValidationRule explicitly is to set the ValidatesOnDataErrors property to true on
your Binding or MultiBinding object.
You can also create your own validation rule by deriving from the ValidationRule class and
implementing the Validate method. The following example shows the rule used by the Add
Product Listing "Start Date" TextBox from the What is data binding section.
C#
public class FutureDateRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo
cultureInfo)
{
// Test if date is valid
if (DateTime.TryParse(value.ToString(), out DateTime date))
{
// Date is not in the future, fail
if (DateTime.Now > date)
return new ValidationResult(false, "Please enter a date in the
future.");
}
else
{
// Date is not a valid date, fail
return new ValidationResult(false, "Value is not a valid date.");
}
The StartDateEntryForm TextBox uses this FutureDateRule, as shown in the following example.
XAML
Because the UpdateSourceTrigger value is PropertyChanged, the binding engine updates the
source value on every keystroke, which means it also checks every rule in the ValidationRules
collection on every keystroke. We discuss this further in the Validation Process section.
XAML
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="20">!</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
The AdornedElementPlaceholder element specifies where the control being adorned should be
placed.
In addition, you may also use a ToolTip to display the error message. Both the
StartDateEntryForm and the StartPriceEntryFormTextBoxes use the style textStyleTextBox, which
creates a ToolTip that displays the error message. The following example shows the definition
of textStyleTextBox. The attached property Validation.HasError is true when one or more of the
bindings on the properties of the bound element are in error.
XAML
With the custom ErrorTemplate and the ToolTip, the StartDateEntryForm TextBox looks like the
following when there's a validation error.
If your Binding has associated validation rules but you do not specify an ErrorTemplate on the
bound control, a default ErrorTemplate will be used to notify users when there's a validation
error. The default ErrorTemplate is a control template that defines a red border in the adorner
layer. With the default ErrorTemplate and the ToolTip, the UI of the StartPriceEntryForm TextBox
looks like the following when there's a validation error.
For an example of how to provide logic to validate all controls in a dialog box, see the Custom
Dialog Boxes section in the Dialog boxes overview.
Validation process
Validation usually occurs when the value of a target is transferred to the binding source
property. This transfer occurs on TwoWay and OneWayToSource bindings. To reiterate, what
causes a source update depends on the value of the UpdateSourceTrigger property, as
described in the What triggers source updates section.
The following items describe the validation process. If a validation error or other type of error
occurs at any time during this process, the process is halted:
1. The binding engine checks if there are any custom ValidationRule objects defined whose
ValidationStep is set to RawProposedValue for that Binding, in which case it calls the
Validate method on each ValidationRule until one of them runs into an error or until all of
them pass.
3. If the converter succeeds, the binding engine checks if there are any custom
ValidationRule objects defined whose ValidationStep is set to ConvertedProposedValue
for that Binding, in which case it calls the Validate method on each ValidationRule that has
ValidationStep set to ConvertedProposedValue until one of them runs into an error or
until all of them pass.
5. The binding engine checks if there are any custom ValidationRule objects defined whose
ValidationStep is set to UpdatedValue for that Binding, in which case it calls the Validate
method on each ValidationRule that has ValidationStep set to UpdatedValue until one of
them runs into an error or until all of them pass. If a DataErrorValidationRule is associated
with a binding and its ValidationStep is set to the default, UpdatedValue, the
DataErrorValidationRule is checked at this point. At this point any binding that has the
ValidatesOnDataErrors set to true is checked.
6. The binding engine checks if there are any custom ValidationRule objects defined whose
ValidationStep is set to CommittedValue for that Binding, in which case it calls the
Validate method on each ValidationRule that has ValidationStep set to CommittedValue
until one of them runs into an error or until all of them pass.
If a ValidationRule doesn't pass at any time throughout this process, the binding engine creates
a ValidationError object and adds it to the Validation.Errors collection of the bound element.
Before the binding engine runs the ValidationRule objects at any given step, it removes any
ValidationError that was added to the Validation.Errors attached property of the bound element
during that step. For example, if a ValidationRule whose ValidationStep is set to UpdatedValue
failed, the next time the validation process occurs, the binding engine removes that
ValidationError immediately before it calls any ValidationRule that has ValidationStep set to
UpdatedValue.
When Validation.Errors isn't empty, the Validation.HasError attached property of the element is
set to true . Also, if the NotifyOnValidationError property of the Binding is set to true , then the
binding engine raises the Validation.Error attached event on the element.
Also note that a valid value transfer in either direction (target to source or source to target)
clears the Validation.Errors attached property.
If the binding either has an ExceptionValidationRule associated with it, or had the
ValidatesOnExceptions property is set to true and an exception is thrown when the binding
engine sets the source, the binding engine checks to see if there's a
UpdateSourceExceptionFilter. You can use the UpdateSourceExceptionFilter callback to provide
a custom handler for handling exceptions. If an UpdateSourceExceptionFilter isn't specified on
the Binding, the binding engine creates a ValidationError with the exception and adds it to the
Validation.Errors collection of the bound element.
Debugging mechanism
You can set the attached property PresentationTraceSources.TraceLevel on a binding-related
object to receive information about the status of a specific binding.
See also
Data binding demo
Binding declarations overview
Binding sources overview
DataErrorValidationRule
What are Binding sources?
Article • 05/07/2025
In data binding, the binding source object refers to the object you obtain data from. This article
discusses the types of objects you can use as the binding source, like .NET CLR objects, XML,
and DependencyObject objects.
You can bind to public properties, sub-properties, and indexers of any common language
runtime (CLR) object. The binding engine uses CLR reflection to get the values of the
properties. Objects that implement ICustomTypeDescriptor or have a registered
TypeDescriptionProvider also work with the binding engine.
For more information about how to implement a class that can serve as a binding source,
see Implementing a binding source on your objects later in this article.
Dynamic objects
You can bind to available properties and indexers of an object that implements the
IDynamicMetaObjectProvider interface. If you can access the member in code, you can
bind to it. For example, if a dynamic object enables you to access a member in code via
SomeObject.AProperty , you can bind to it by setting the binding path to AProperty .
ADO.NET objects
You can bind to ADO.NET objects, such as DataTable. The ADO.NET DataView implements
the IBindingList interface, which provides change notifications that the binding engine
listens for.
XML objects
You can bind to and run XPath queries on an XmlNode, XmlDocument, or XmlElement. A
convenient way to access XML data that is the binding source in markup is to use an
XmlDataProvider object. For more information, see Bind to XML Data Using an
XMLDataProvider and XPath Queries (.NET Framework).
You can also bind to an XElement or XDocument, or bind to the results of queries run on
objects of these types by using LINQ to XML. A convenient way to use LINQ to XML to
access XML data that is the binding source in markup is to use an ObjectDataProvider
object. For more information, see Bind to XDocument, XElement, or LINQ for XML Query
Results (.NET Framework).
DependencyObject objects
You can bind to dependency properties of any DependencyObject. For an example, see
Bind the Properties of Two Controls (.NET Framework).
Each property that needs to notify a binding target that it's changed, has a corresponding
PropertyNameChanged event, where PropertyName is the name of the property. You raise
If your binding source implements one of these notification mechanisms, target updates
happen automatically. If for any reason your binding source doesn't provide the proper
property changed notifications, you can use the UpdateTarget method to update the target
property explicitly.
Other characteristics
The following list provides other important points to note:
Data objects that serve as binding sources can be declared in XAML as resources,
provided they have a parameterless constructor. Otherwise, you must create the data
object in code and directly assign it to either the data context of your XAML object tree,
or as the binding source of binding.
The properties you use as binding source properties must be public properties of your
class. Explicitly defined interface properties can't be accessed for binding purposes, nor
can protected, private, internal, or virtual properties that have no base implementation.
The type of the property declared in your class is the type that is passed to the binding.
However, the type ultimately used by the binding depends on the type of the binding
target property, not of the binding source property. If there's a difference in type, you
might want to write a converter to handle how your custom property is initially passed to
the binding. For more information, see IValueConverter.
You may need to apply custom logic so that the data is meaningful to your bound target
property. The custom logic may be in the form of a custom converter or a DataTemplate. For
more information about converters, see Data conversion. For more information about data
templates, see Data Templating Overview (.NET Framework).
When you specify a collection as a binding source, WPF doesn't bind directly to the collection.
Instead, WPF actually binds to the collection's default view. For information about default
views, see Using a default view.
If you have an advanced scenario and you want to implement your own collection, consider
using the IList interface. This interface provides a non-generic collection of objects that can be
individually accessed by index, which can improve performance.
See also
ObjectDataProvider
XmlDataProvider
Data binding overview
Binding sources overview
Overview of WPF data binding with LINQ to XML (.NET Framework)
Optimizing Performance: Data Binding (.NET Framework)
Data Templating Overview
Article • 05/07/2025
The WPF data templating model provides you with great flexibility to define the presentation
of your data. WPF controls have built-in functionality to support the customization of data
presentation. This topic first demonstrates how to define a DataTemplate and then introduces
other data templating features, such as the selection of templates based on custom logic and
the support for the display of hierarchical data.
Prerequisites
This topic focuses on data templating features and is not an introduction of data binding
concepts. For information about basic data binding concepts, see the Data Binding Overview.
DataTemplate is about the presentation of data and is one of the many features provided by
the WPF styling and templating model. For an introduction of the WPF styling and templating
model, such as how to use a Style to set properties on controls, see the Styling and Templating
topic.
In addition, it is important to understand Resources , which are essentially what enable objects
such as Style and DataTemplate to be reusable. For more information on resources, see XAML
Resources.
XAML
<Window x:Class="SDKSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SDKSample"
Title="Introduction to Data Templating Sample">
<Window.Resources>
<local:Tasks x:Key="myTodoList"/>
XAML
</Window.Resources>
<StackPanel>
<TextBlock Name="blah" FontSize="20" Text="My Task List:"/>
<ListBox Width="400" Margin="10"
ItemsSource="{Binding Source={StaticResource myTodoList}}"/>
XAML
</StackPanel>
</Window>
Without a DataTemplate
Without a DataTemplate, our ListBox currently looks like this:
What's happening is that without any specific instructions, the ListBox by default calls ToString
when trying to display the objects in the collection. Therefore, if the Task object overrides the
ToString method, then the ListBox displays the string representation of each source object in
For example, if the Task class overrides the ToString method this way, where name is the field
for the TaskName property:
C#
XAML
The underlying data for the examples in this topic is a collection of CLR objects. If you are
binding to XML data, the fundamental concepts are the same, but there is a slight syntactic
difference. For example, instead of having Path=TaskName , you would set XPath to @TaskName (if
TaskName is an attribute of your XML node).
XAML
<Window.Resources>
XAML
<DataTemplate x:Key="myTaskTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
XAML
</Window.Resources>
XAML
XAML
This DataTemplate gets applied automatically to all Task objects. Note that in this case the
x:Key is set implicitly. Therefore, if you assign this DataTemplate an x:Key value, you are
overriding the implicit x:Key and the DataTemplate would not be applied automatically.
If you are binding a ContentControl to a collection of Task objects, the ContentControl does
not use the above DataTemplate automatically. This is because the binding on a
ContentControl needs more information to distinguish whether you want to bind to an entire
collection or the individual objects. If your ContentControl is tracking the selection of an
ItemsControl type, you can set the Path property of the ContentControl binding to " / " to
indicate that you are interested in the current item. For an example, see Bind to a Collection
and Display Information Based on Selection. Otherwise, you need to specify the DataTemplate
explicitly by setting the ContentTemplate property.
The DataType property is particularly useful when you have a CompositeCollection of different
types of data objects. For an example, see Implement a CompositeCollection.
<DataTemplate x:Key="myTaskTemplate">
<Border Name="border" BorderBrush="Aqua" BorderThickness="1"
Padding="5" Margin="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Task Name:"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=TaskName}" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Description:"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="Priority:"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Priority}"/>
</Grid>
</Border>
XAML
</DataTemplate>
The following screenshot shows the ListBox with this modified DataTemplate:
We can set HorizontalContentAlignment to Stretch on the ListBox to make sure the width of
the items takes up the entire space:
XAML
<ListBox Width="400" Margin="10"
ItemsSource="{Binding Source={StaticResource myTodoList}}"
ItemTemplate="{StaticResource myTaskTemplate}"
HorizontalContentAlignment="Stretch"/>
With the HorizontalContentAlignment property set to Stretch, the ListBox now looks like this:
In the following example, the DataTrigger sets the BorderBrush of the element named border
to Yellow if the TaskType property is TaskType.Home .
XAML
<DataTemplate x:Key="myTaskTemplate">
XAML
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=TaskType}">
<DataTrigger.Value>
<local:TaskType>Home</local:TaskType>
</DataTrigger.Value>
<Setter TargetName="border" Property="BorderBrush" Value="Yellow"/>
</DataTrigger>
</DataTemplate.Triggers>
XAML
</DataTemplate>
Our application now looks like the following. Home tasks appear with a yellow border and
office tasks appear with an aqua border:
In this example the DataTrigger uses a Setter to set a property value. The trigger classes also
have the EnterActions and ExitActions properties that allow you to start a set of actions such as
animations. In addition, there is also a MultiDataTrigger class that allows you to apply changes
based on multiple data-bound property values.
An alternative way to achieve the same effect is to bind the BorderBrush property to the
TaskType property and use a value converter to return the color based on the TaskType value.
Creating the above effect using a converter is slightly more efficient in terms of performance.
Additionally, creating your own converter gives you more flexibility because you are supplying
your own logic. Ultimately, which technique you choose depends on your scenario and your
preference. For information about how to write a converter, see IValueConverter.
For example, when a Task object has a Priority value of 1 , you may want to give it a
completely different look to serve as an alert for yourself. In that case, you create a
DataTemplate for the display of the high-priority Task objects. Let's add the following
DataTemplate to the resources section:
XAML
<DataTemplate x:Key="importantTaskTemplate">
<DataTemplate.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="20"/>
</Style>
</DataTemplate.Resources>
<Border Name="border" BorderBrush="Red" BorderThickness="1"
Padding="5" Margin="5">
<DockPanel HorizontalAlignment="Center">
<TextBlock Text="{Binding Path=Description}" />
<TextBlock>!</TextBlock>
</DockPanel>
</Border>
</DataTemplate>
This example uses the DataTemplate.Resources property. Resources defined in that section are
shared by the elements within the DataTemplate.
To supply logic to choose which DataTemplate to use based on the Priority value of the data
object, create a subclass of DataTemplateSelector and override the SelectTemplate method. In
the following example, the SelectTemplate method provides logic to return the appropriate
template based on the value of the Priority property. The template to return is found in the
resources of the enveloping Window element.
C#
using System.Windows;
using System.Windows.Controls;
namespace SDKSample
{
public class TaskListDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (taskitem.Priority == 1)
return
element.FindResource("importantTaskTemplate") as
DataTemplate;
else
return
element.FindResource("myTaskTemplate") as DataTemplate;
}
return null;
}
}
}
XAML
<Window.Resources>
XAML
<local:TaskListDataTemplateSelector x:Key="myDataTemplateSelector"/>
XAML
</Window.Resources>
To use the template selector resource, assign it to the ItemTemplateSelector property of the
ListBox. The ListBox calls the SelectTemplate method of the TaskListDataTemplateSelector for
each of the items in the underlying collection. The call passes the data object as the item
parameter. The DataTemplate that is returned by the method is then applied to that data
object.
XAML
With the template selector in place, the ListBox now appears as follows:
This concludes our discussion of this example. For the complete sample, see Introduction to
Data Templating Sample .
Styling and Templating an ItemsControl
Even though the ItemsControl is not the only control type that you can use a DataTemplate
with, it is a very common scenario to bind an ItemsControl to a collection. In the What Belongs
in a DataTemplate section we discussed that the definition of your DataTemplate should only
be concerned with the presentation of data. In order to know when it is not suitable to use a
DataTemplate it is important to understand the different style and template properties
provided by the ItemsControl. The following example is designed to illustrate the function of
each of these properties. The ItemsControl in this example is bound to the same Tasks
collection as in the previous example. For demonstration purposes, the styles and templates in
this example are all declared inline.
XAML
<ItemsControl Margin="10"
ItemsSource="{Binding Source={StaticResource myTodoList}}">
<!--The ItemsControl has no default visual appearance.
Use the Template property to specify a ControlTemplate to define
the appearance of an ItemsControl. The ItemsPresenter uses the specified
ItemsPanelTemplate (see below) to layout the items. If an
ItemsPanelTemplate is not specified, the default is used. (For ItemsControl,
the default is an ItemsPanelTemplate that specifies a StackPanel.-->
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Border BorderBrush="Aqua" BorderThickness="1" CornerRadius="15">
<ItemsPresenter/>
</Border>
</ControlTemplate>
</ItemsControl.Template>
<!--Use the ItemsPanel property to specify an ItemsPanelTemplate
that defines the panel that is used to hold the generated items.
In other words, use this property if you want to affect
how the items are laid out.-->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!--Use the ItemTemplate to set a DataTemplate to define
the visualization of the data objects. This DataTemplate
specifies that each data object appears with the Proriity
and TaskName on top of a silver ellipse.-->
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="18"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</DataTemplate.Resources>
<Grid>
<Ellipse Fill="Silver"/>
<StackPanel>
<TextBlock Margin="3,3,3,0"
Text="{Binding Path=Priority}"/>
<TextBlock Margin="3,0,3,7"
Text="{Binding Path=TaskName}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<!--Use the ItemContainerStyle property to specify the appearance
of the element that contains the data. This ItemContainerStyle
gives each item container a margin and a width. There is also
a trigger that sets a tooltip that shows the description of
the data object when the mouse hovers over the item container.-->
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Control.Width" Value="100"/>
<Setter Property="Control.Margin" Value="5"/>
<Style.Triggers>
<Trigger Property="Control.IsMouseOver" Value="True">
<Setter Property="Control.ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=Content.Description}"/>
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
Note that instead of using the ItemTemplate, you can use the ItemTemplateSelector. Refer to
the previous section for an example. Similarly, instead of using the ItemContainerStyle, you
have the option to use the ItemContainerStyleSelector.
Two other style-related properties of the ItemsControl that are not shown here are GroupStyle
and GroupStyleSelector.
XAML
<Window x:Class="SDKSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="HierarchicalDataTemplate Sample"
xmlns:src="clr-namespace:SDKSample">
<DockPanel>
<DockPanel.Resources>
<src:ListLeagueList x:Key="MyList"/>
<TreeView>
<TreeViewItem ItemsSource="{Binding Source={StaticResource MyList}}"
Header="My Soccer Leagues" />
</TreeView>
</DockPanel>
</Window>
The example shows that with the use of HierarchicalDataTemplate, you can easily display list
data that contains other lists. The following is a screenshot of the example.
See also
Data Binding
Find DataTemplate-Generated Elements
Styling and Templating
Data Binding Overview
GridView Column Header Styles and Templates Overview
What are binding declarations?
Article • 05/07/2025
Typically, developers declare the bindings directly in the XAML markup of the UI elements they
want to bind data to. However, you can also declare bindings in code. This article describes
how to declare bindings in both XAML and in code.
Prerequisites
Before reading this article, it's important that you're familiar with the concept and usage of
markup extensions. For more information about markup extensions, see Markup Extensions
and WPF XAML.
This article doesn't cover data binding concepts. For a discussion of data binding concepts, see
Data binding overview.
When creating binding declaration strings in markup, they must be attached to the specific
dependency property of a target object. The following example shows how to bind the
TextBox.Text property using the binding extension, specifying the Source and Path properties.
XAML
The previous example uses a simple data object type of Person . The following snippet is the
code for that object:
C#
class Person
{
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
You can specify most of the properties of the Binding class this way. For more information
about the binding extension and for a list of Binding properties that cannot be set using the
binding extension, see the Binding Markup Extension (.NET Framework) overview.
For an example on creating a binding in XAML, see How to create a data binding.
The previous section demonstrated how to bind with a XAML extension. The following example
demonstrates doing the same binding but uses object element syntax:
XAML
<TextBlock>
<TextBlock.Text>
<Binding Source="{StaticResource myDataSource}" Path="Name"/>
</TextBlock.Text>
</TextBlock>
For more information about the different terms, see XAML Syntax In Detail (.NET Framework).
C#
// New binding object using the path of 'Name' for whatever source object is
used
var nameBindingObject = new Binding("Name");
The previous example uses a simple data object type of Person . The following is the code for
that object:
C#
class Person
{
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
In the simplest case, the Path property value is the name of the property of the source
object to use for the binding, such as Path=PropertyName .
Subproperties of a property can be specified by a similar syntax as in C#. For instance, the
clause Path=ShoppingCart.Order sets the binding to the subproperty Order of the object
or property ShoppingCart .
To bind to an attached property, place parentheses around the attached property. For
example, to bind to the attached property DockPanel.Dock, the syntax is Path=
(DockPanel.Dock) .
Indexers of a property can be specified within square brackets following the property
name where the indexer is applied. For instance, the clause Path=ShoppingCart[0] sets the
binding to the index that corresponds to how your property's internal indexing handles
the literal string "0". Nested indexers are also supported.
Inside indexers. You can have multiple indexer parameters separated by commas ( , ). The
type of each parameter can be specified with parentheses. For example, you can have
Path="[(sys:Int32)42,(sys:Int32)24]" , where sys is mapped to the System namespace.
When the source is a collection view, the current item can be specified with a slash ( / ).
For example, the clause Path=/ sets the binding to the current item in the view. When the
source is a collection, this syntax specifies the current item of the default collection view.
Property names and slashes can be combined to traverse properties that are collections.
For example, Path=/Offices/ManagerName specifies the current item of the source
collection, which contains an Offices property that is also a collection. Its current item is
an object that contains a ManagerName property.
Optionally, a period ( . ) path can be used to bind to the current source. For example,
Text="{Binding}" is equivalent to Text="{Binding Path=.}" .
Escaping mechanism
Inside indexers ( [ ] ), the caret character ( ^ ) escapes the next character.
If you set Path in XAML, you also need to escape (using XML entities) certain characters
that are special to the XML language definition:
Use & to escape the character " & ".
Additionally, if you describe the entire binding in an attribute using the markup extension
syntax, you need to escape (using backslash \ ) characters that are special to the WPF
markup extension parser:
Binding direction
Use the Binding.Mode property to specify the direction of the binding. The following modes
are the available options for binding updates:
ノ Expand table
BindingMode.TwoWay Updates the target property or the property whenever either the target
property or the source property changes.
BindingMode.OneWay Updates the target property only when the source property changes.
BindingMode.OneTime Updates the target property only when the application starts or when
the DataContext undergoes a change.
BindingMode.OneWayToSource Updates the source property when the target property changes.
XAML
For TwoWay or OneWayToSource bindings, you can control the timing of the source updates
by setting the UpdateSourceTrigger property. For more information, see UpdateSourceTrigger.
Default behaviors
The default behavior is as follows if not specified in the declaration:
A default converter is created that tries to do a type conversion between the binding
source value and the binding target value. If a conversion cannot be made, the default
converter returns null .
If you don't set ConverterCulture, the binding engine uses the Language property of the
binding target object. In XAML, this defaults to en-US or inherits the value from the root
element (or any element) of the page, if one has been explicitly set.
As long as the binding already has a data context (for example, the inherited data context
coming from a parent element), and whatever item or collection being returned by that
context is appropriate for binding without requiring further path modification, a binding
declaration can have no clauses at all: {Binding} . This is often the way a binding is
specified for data styling, where the binding acts upon a collection. For more information,
see Using Entire Objects as a Binding Source.
The default Mode varies between one-way and two-way depending on the dependency
property that is being bound. You can always declare the binding mode explicitly to
ensure that your binding has the desired behavior. In general, user-editable control
properties, such as TextBox.Text and RangeBase.Value, default to two-way bindings, but
most other properties default to one-way bindings.
See also
Data binding overview
Binding sources overview
How to create a data binding
PropertyPath XAML Syntax (.NET Framework)
Data binding how-to topics
Article • 05/07/2025
The topics in this section describe how to use data binding to bind elements to data from a
variety of data sources in the form of common language runtime (CLR) objects and XML.
In this section
Create a Simple Binding
Specify the Binding Source
Make Data Available for Binding in XAML
Control When the TextBox Text Updates the Source
Specify the Direction of the Binding
Bind to a Collection and Display Information Based on Selection
Bind to an Enumeration
Bind the Properties of Two Controls
Implement Binding Validation
Implement Validation Logic on Custom Objects
Get the Binding Object from a Bound Target Property
Implement a CompositeCollection
Convert Bound Data
Create a Binding in Code
Get the Default View of a Data Collection
Navigate Through the Objects in a Data CollectionView
Filter Data in a View
Sort Data in a View
Sort and Group Data Using a View in XAML
Use the Master-Detail Pattern with Hierarchical Data
Use the Master-Detail Pattern with Hierarchical XML Data
Produce a Value Based on a List of Bound Items
Implement Property Change Notification
Create and Bind to an ObservableCollection
Implement PriorityBinding
Bind to XML Data Using an XMLDataProvider and XPath Queries
Bind to XDocument, XElement, or LINQ for XML Query Results
Bind to the Results of a LINQ Query
Use XML Namespaces in Data Binding
Bind to an ADO.NET Data Source
Bind to a Method
Set Up Notification of Binding Updates
Clear Bindings
Find DataTemplate-Generated Elements
Reference
System.Windows.Data
Binding
DataTemplate
DataTemplateSelector
Related sections
Data binding in WPF
Data binding performance
How to create a data binding
Article • 05/07/2025
This article describes how to create a binding XAML. The example uses a data object that
represents an employee at a company. This data object is bound to a XAML window that uses
TextBlock controls to list the employee's details. You'll create a UI that looks like the following
image:
To learn more about data binding, see Data binding overview in WPF.
C#
using System;
using System.ComponentModel;
namespace ArticleSample
{
public class Employee : INotifyPropertyChanged
{
private decimal _salary;
public event PropertyChangedEventHandler? PropertyChanged;
) Important
The following snippet is taken from a C# project. If you're using Visual Basic, the
x:Class should be declared without the ArticleSample namespace. You can see
XAML
<Window x:Class="ArticleSample.EmployeeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArticleSample"
Title="" Height="250" Width="300">
<Window.Resources>
<local:Employee x:Key="EmployeeExample" FirstName="Niki"
LastName="Demetriou"
HireDate="2022-02-16"
Salary="5012.00"
Title="Content Artist" />
</Window.Resources>
<StackPanel DataContext="{StaticResource EmployeeExample}">
<Label FontSize="32">Employee</Label>
<Border BorderBrush="Gray" BorderThickness="2" />
<Grid Grid.Row="1" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
The namespace of the code won't match your project's namespace, unless you created a
project named ArticleSample. You can copy and paste the Window.Resources and root element
( StackPanel ) into you're MainWindow if you created a new project.
To better understand how the previous XAML is using data binding, consider the following
points:
Typically the data object is passed to or associated with the Window. This example
hardcodes the employee for demonstration purposes.
XAML
<Window.Resources>
<local:Employee x:Key="EmployeeExample" FirstName="Niki"
LastName="Demetriou"
HireDate="2022-02-16"
Salary="5012.00"
Title="Content Artist" />
</Window.Resources>
The root element ( StackPanel ) has its data context set to the hardcoded Employee
instance.
The child elements inherit their DataContext from the parent, unless explicitly set.
XAML
The properties of the Employee instance are bound to the TextBlock controls.
The Binding doesn't specify a BindingSource , so the DataContext is used as the source.
XAML
A TextBox control is bound with TwoWay mode, allowing the TextBox to change the
Employee.Salary property.
XAML
<TextBox Text="{Binding Salary, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged, StringFormat=C0}" Width="100" />
Related content
Data Binding Overview
How to: Specify the Binding Source
Article • 05/07/2025
In data binding, the binding source object refers to the object you obtain your data from. This
topic describes the different ways of specifying the binding source.
Example
If you are binding several properties to a common source, you want to use the DataContext
property, which provides a convenient way to establish a scope within which all data-bound
properties inherit a common source.
In the following example, the data context is established on the root element of the
application. This allows all child elements to inherit that data context. Data for the binding
comes from a custom data class, NetIncome , referenced directly through a mapping and given
the resource key of incomeDataSource .
XAML
<Grid
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.DirectionalBinding"
xmlns:c="clr-namespace:SDKSample"
Name="Page1"
>
<Grid.Resources>
<c:NetIncome x:Key="incomeDataSource"/>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Padding" Value="8"/>
</Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="0,6,0,0"/>
</Style>
</Grid.Resources>
<Grid.DataContext>
<Binding Source="{StaticResource incomeDataSource}"/>
</Grid.DataContext>
XAML
</Grid>
C#
public class NetIncome : INotifyPropertyChanged
{
private int totalIncome = 5000;
private int rent = 2000;
private int food = 0;
private int misc = 0;
private int savings = 0;
public NetIncome()
{
savings = totalIncome - (rent+food+misc);
}
7 Note
The above example instantiates the object in markup and uses it as a resource. If you want
to bind to an object that has already been instantiated in code, you need to set the
DataContext property programmatically. For an example, see Make Data Available for
Binding in XAML.
Alternatively, if you want to specify the source on your individual bindings explicitly, you have
the following options. These take precedence over the inherited data context.
ノ Expand table
Property Description
Source You use this property to set the source to an instance of an object. If you do not need
the functionality of establishing a scope in which several properties inherit the same data
context, you can use the Source property instead of the DataContext property. For more
information, see Source.
RelativeSource This is useful when you want to specify the source relative to where your binding target
is. Some common scenarios where you may use this property is when you want to bind
one property of your element to another property of the same element or if you are
defining a binding in a style or a template. For more information, see RelativeSource.
ElementName You specify a string that represents the element you want to bind to. This is useful when
you want to bind to the property of another element on your application. For example, if
you want to use a Slider to control the height of another control in your application, or if
you want to bind the Content of your control to the SelectedValue property of your
ListBox control. For more information, see ElementName.
See also
FrameworkElement.DataContext
FrameworkContentElement.DataContext
Property Value Inheritance
Data Binding Overview
Binding Declarations Overview
How-to Topics
How to: Make Data Available for Binding in
XAML
Article • 05/07/2025
This topic discusses various ways you can make data available for binding in Extensible
Application Markup Language (XAML), depending on the needs of your application.
Example
If you have a common language runtime (CLR) object you would like to bind to from XAML,
one way you can make the object available for binding is to define it as a resource and give it
an x:Key . In the following example, you have a Person object with a string property named
PersonName . The Person object (in the line shown highlighted that contains the <src> element)
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:SDKSample"
SizeToContent="WidthAndHeight"
Title="Simple Data Binding Sample">
<Window.Resources>
<src:Person x:Key="myDataSource" PersonName="Joe"/>
<Style TargetType="{x:Type Label}">
<Setter Property="DockPanel.Dock" Value="Top"/>
<Setter Property="FontSize" Value="12"/>
</Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="25"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
</Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="25"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
<Setter Property="Padding" Value="3"/>
</Style>
</Window.Resources>
<Border Margin="5" BorderBrush="Aqua" BorderThickness="1" Padding="8"
CornerRadius="3">
<DockPanel Width="200" Height="100" Margin="35">
<Label>Enter a Name:</Label>
<TextBox>
<TextBox.Text>
<Binding Source="{StaticResource myDataSource}" Path="PersonName"
UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
You can then bind the TextBlock control to the object in XAML, as the highlighted line that
contains the <TextBlock> element shows.
Alternatively, you can use the ObjectDataProvider class, as in the following example:
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:SDKSample"
xmlns:system="clr-namespace:System;assembly=mscorlib"
SizeToContent="WidthAndHeight"
Title="Simple Data Binding Sample">
<Window.Resources>
<ObjectDataProvider x:Key="myDataSource" ObjectType="{x:Type src:Person}">
<ObjectDataProvider.ConstructorParameters>
<system:String>Joe</system:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
<Style TargetType="{x:Type Label}">
<Setter Property="DockPanel.Dock" Value="Top"/>
<Setter Property="FontSize" Value="12"/>
</Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="25"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
</Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="25"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
</Style>
</Window.Resources>
You define the binding the same way, as the highlighted line that contains the <TextBlock>
element shows.
In this particular example, the result is the same: you have a TextBlock with the text content
Joe . However, the ObjectDataProvider class provides functionality such as the ability to bind to
the result of a method. You can choose to use the ObjectDataProvider class if you need the
functionality it provides.
However, if you are binding to an object that has already been created, you need to set the
DataContext in code, as in the following example.
C#
DataSet myDataSet;
To access XML data for binding using the XmlDataProvider class, see Bind to XML Data Using
an XMLDataProvider and XPath Queries. To access XML data for binding using the
ObjectDataProvider class, see Bind to XDocument, XElement, or LINQ for XML Query Results.
For information about many ways you can specify the data you are binding to, see Specify the
Binding Source. For information about what types of data you can bind to or how to
implement your own common language runtime (CLR) objects for binding, see Binding Sources
Overview.
See also
Data Binding Overview
How-to Topics
How to: Control When the TextBox Text
Updates the Source
Article • 05/07/2025
This topic describes how to use the UpdateSourceTrigger property to control the timing of
binding source updates. The topic uses the TextBox control as an example.
Example
The TextBox.Text property has a default UpdateSourceTrigger value of LostFocus. This means if
an application has a TextBox with a data-bound TextBox.Text property, the text you type into
the TextBox does not update the source until the TextBox loses focus (for instance, when you
click away from the TextBox).
If you want the source to be updated as you type, set the UpdateSourceTrigger of the binding
to PropertyChanged. In the following example, the highlighted lines of code show that the
Text properties of both the TextBox and the TextBlock are bound to the same source property.
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:SDKSample"
xmlns:system="clr-namespace:System;assembly=mscorlib"
SizeToContent="WidthAndHeight"
Title="Simple Data Binding Sample">
<Window.Resources>
<ObjectDataProvider x:Key="myDataSource" ObjectType="{x:Type src:Person}">
<ObjectDataProvider.ConstructorParameters>
<system:String>Joe</system:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
<Style TargetType="{x:Type Label}">
<Setter Property="DockPanel.Dock" Value="Top"/>
<Setter Property="FontSize" Value="12"/>
</Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="25"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
</Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="25"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
</Style>
</Window.Resources>
As a result, the TextBlock shows the same text (because the source changes) as the user enters
text into the TextBox, as illustrated by the following screenshot of the sample:
If you have a dialog or a user-editable form and you want to defer source updates until the
user is finished editing the fields and clicks "OK", you can set the UpdateSourceTrigger value of
your bindings to Explicit, as in the following example:
XAML
<TextBox Name="itemNameTextBox"
Text="{Binding Path=ItemName, UpdateSourceTrigger=Explicit}" />
When you set the UpdateSourceTrigger value to Explicit, the source value only changes when
the application calls the UpdateSource method. The following example shows how to call
UpdateSource for itemNameTextBox :
C#
7 Note
You can use the same technique for properties of other controls, but keep in mind that
most other properties have a default UpdateSourceTrigger value of PropertyChanged.
For more information, see the UpdateSourceTrigger property page.
7 Note
The UpdateSourceTrigger property deals with source updates and therefore is only
relevant for TwoWay or OneWayToSource bindings. For TwoWay and OneWayToSource
bindings to work, the source object needs to provide property change notifications. You
can refer to the samples cited in this topic for more information. In addition, you can look
at Implement Property Change Notification.
See also
How-to Topics
What are binding declarations?
Article • 05/07/2025
Typically, developers declare the bindings directly in the XAML markup of the UI elements they
want to bind data to. However, you can also declare bindings in code. This article describes
how to declare bindings in both XAML and in code.
Prerequisites
Before reading this article, it's important that you're familiar with the concept and usage of
markup extensions. For more information about markup extensions, see Markup Extensions
and WPF XAML.
This article doesn't cover data binding concepts. For a discussion of data binding concepts, see
Data binding overview.
When creating binding declaration strings in markup, they must be attached to the specific
dependency property of a target object. The following example shows how to bind the
TextBox.Text property using the binding extension, specifying the Source and Path properties.
XAML
The previous example uses a simple data object type of Person . The following snippet is the
code for that object:
C#
class Person
{
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
You can specify most of the properties of the Binding class this way. For more information
about the binding extension and for a list of Binding properties that cannot be set using the
binding extension, see the Binding Markup Extension (.NET Framework) overview.
For an example on creating a binding in XAML, see How to create a data binding.
The previous section demonstrated how to bind with a XAML extension. The following example
demonstrates doing the same binding but uses object element syntax:
XAML
<TextBlock>
<TextBlock.Text>
<Binding Source="{StaticResource myDataSource}" Path="Name"/>
</TextBlock.Text>
</TextBlock>
For more information about the different terms, see XAML Syntax In Detail (.NET Framework).
C#
// New binding object using the path of 'Name' for whatever source object is
used
var nameBindingObject = new Binding("Name");
The previous example uses a simple data object type of Person . The following is the code for
that object:
C#
class Person
{
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
In the simplest case, the Path property value is the name of the property of the source
object to use for the binding, such as Path=PropertyName .
Subproperties of a property can be specified by a similar syntax as in C#. For instance, the
clause Path=ShoppingCart.Order sets the binding to the subproperty Order of the object
or property ShoppingCart .
To bind to an attached property, place parentheses around the attached property. For
example, to bind to the attached property DockPanel.Dock, the syntax is Path=
(DockPanel.Dock) .
Indexers of a property can be specified within square brackets following the property
name where the indexer is applied. For instance, the clause Path=ShoppingCart[0] sets the
binding to the index that corresponds to how your property's internal indexing handles
the literal string "0". Nested indexers are also supported.
Inside indexers. You can have multiple indexer parameters separated by commas ( , ). The
type of each parameter can be specified with parentheses. For example, you can have
Path="[(sys:Int32)42,(sys:Int32)24]" , where sys is mapped to the System namespace.
When the source is a collection view, the current item can be specified with a slash ( / ).
For example, the clause Path=/ sets the binding to the current item in the view. When the
source is a collection, this syntax specifies the current item of the default collection view.
Property names and slashes can be combined to traverse properties that are collections.
For example, Path=/Offices/ManagerName specifies the current item of the source
collection, which contains an Offices property that is also a collection. Its current item is
an object that contains a ManagerName property.
Optionally, a period ( . ) path can be used to bind to the current source. For example,
Text="{Binding}" is equivalent to Text="{Binding Path=.}" .
Escaping mechanism
Inside indexers ( [ ] ), the caret character ( ^ ) escapes the next character.
If you set Path in XAML, you also need to escape (using XML entities) certain characters
that are special to the XML language definition:
Use & to escape the character " & ".
Additionally, if you describe the entire binding in an attribute using the markup extension
syntax, you need to escape (using backslash \ ) characters that are special to the WPF
markup extension parser:
Binding direction
Use the Binding.Mode property to specify the direction of the binding. The following modes
are the available options for binding updates:
ノ Expand table
BindingMode.TwoWay Updates the target property or the property whenever either the target
property or the source property changes.
BindingMode.OneWay Updates the target property only when the source property changes.
BindingMode.OneTime Updates the target property only when the application starts or when
the DataContext undergoes a change.
BindingMode.OneWayToSource Updates the source property when the target property changes.
XAML
For TwoWay or OneWayToSource bindings, you can control the timing of the source updates
by setting the UpdateSourceTrigger property. For more information, see UpdateSourceTrigger.
Default behaviors
The default behavior is as follows if not specified in the declaration:
A default converter is created that tries to do a type conversion between the binding
source value and the binding target value. If a conversion cannot be made, the default
converter returns null .
If you don't set ConverterCulture, the binding engine uses the Language property of the
binding target object. In XAML, this defaults to en-US or inherits the value from the root
element (or any element) of the page, if one has been explicitly set.
As long as the binding already has a data context (for example, the inherited data context
coming from a parent element), and whatever item or collection being returned by that
context is appropriate for binding without requiring further path modification, a binding
declaration can have no clauses at all: {Binding} . This is often the way a binding is
specified for data styling, where the binding acts upon a collection. For more information,
see Using Entire Objects as a Binding Source.
The default Mode varies between one-way and two-way depending on the dependency
property that is being bound. You can always declare the binding mode explicitly to
ensure that your binding has the desired behavior. In general, user-editable control
properties, such as TextBox.Text and RangeBase.Value, default to two-way bindings, but
most other properties default to one-way bindings.
See also
Data binding overview
Binding sources overview
How to create a data binding
PropertyPath XAML Syntax (.NET Framework)
How to: Bind to a Collection and Display
Information Based on Selection
Article • 05/07/2025
Example
In this example, People is an ObservableCollection<T> of Person classes. This Person class
contains three properties: FirstName , LastName , and HomeTown , all of type string .
XAML
<Window x:Class="SDKSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SDKSample"
Title="Binding to a Collection"
SizeToContent="WidthAndHeight">
<Window.Resources>
<local:People x:Key="MyFriends"/>
XAML
</Window.Resources>
<StackPanel>
<TextBlock FontFamily="Verdana" FontSize="11"
Margin="5,15,0,10" FontWeight="Bold">My Friends:</TextBlock>
<ListBox Width="200" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource MyFriends}}"/>
<TextBlock FontFamily="Verdana" FontSize="11"
Margin="5,15,0,5" FontWeight="Bold">Information:</TextBlock>
<ContentControl Content="{Binding Source={StaticResource MyFriends}}"
ContentTemplate="{StaticResource DetailTemplate}"/>
</StackPanel>
</Window>
The ContentControl uses the following DataTemplate that defines how the information of a
Person is presented:
XAML
<DataTemplate x:Key="DetailTemplate">
<Border Width="300" Height="100" Margin="20"
BorderBrush="Aqua" BorderThickness="1" Padding="8">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="First Name:"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=FirstName}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Last Name:"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=LastName}"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="Home Town:"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=HomeTown}"/>
</Grid>
</Border>
</DataTemplate>
The following is a screenshot of what the example produces. The ContentControl shows the
other properties of the person selected.
1. The ListBox and the ContentControl bind to the same source. The Path properties of both
bindings are not specified because both controls are binding to the entire collection
object.
2. You must set the IsSynchronizedWithCurrentItem property to true for this to work.
Setting this property ensures that the selected item is always set as the CurrentItem.
Alternatively, if the ListBox gets it data from a CollectionViewSource, it synchronizes
selection and currency automatically.
Note that the Person class overrides the ToString method the following way. By default, the
ListBox calls ToString and displays a string representation of each object in the bound
collection. That is why each Person appears as a first name in the ListBox.
C#
See also
Use the Master-Detail Pattern with Hierarchical Data
Use the Master-Detail Pattern with Hierarchical XML Data
Data Binding Overview
Data Templating Overview
How-to Topics
How to bind to an enumeration
Article • 05/07/2025
This example shows how to bind to an enumeration. Unfortunately there isn't a direct way to
use an enumeration as a data binding source. However, the Enum.GetValues(Type) method
returns a collection of values. These values can be wrapped in an ObjectDataProvider and used
as a data source.
The ObjectDataProvider type provides a convenient way to create an object in XAML and use it
as a data source.
XAML
<Window.Resources>
<ObjectDataProvider x:Key="EnumDataSource"
ObjectType="{x:Type sys:Enum}"
MethodName="GetValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="HorizontalAlignment" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
ノ Expand table
Property Description
ObjectType The type of object to be returned by the data provider. In this example,
System.Enum. The sys: XAML namespace is mapped to System .
MethodName The name of the method to run on the System.Enum type. In this example,
Property Description
Enum.GetValues.
Effectively, the XAML is breaking down a method call, method name, parameters, and the
return type. The ObjectDataProvider configured in the previous example is the equivalent
of the following code:
C#
var enumDataSource =
System.Enum.GetValues(typeof(System.Windows.HorizontalAlignment));
2. Reference the ObjectDataProvider resource. The following XAML lists the enumeration
values in a ListBox control:
XAML
Full XAML
The following XAML code represents a simple window that does the following:
XAML
<Window x:Class="ArticleExample.BindEnumFull"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
SizeToContent="WidthAndHeight"
Title="Enum binding">
<Window.Resources>
<ObjectDataProvider x:Key="EnumDataSource"
ObjectType="{x:Type sys:Enum}"
MethodName="GetValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="HorizontalAlignment" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
See also
Data binding overview
Binding sources overview
StaticResource Markup Extension
An alternative way to bind to an enumeration
How to: Bind the Properties of Two
Controls
Article • 05/07/2025
This example shows how to bind the property of one instantiated control to that of another
using the ElementName property.
Example
The following example shows how to bind the Background property of a Canvas to the
SelectedItem.Content property of a ComboBox:
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="460" Height="200"
Title="Binding the Properties of Two Controls">
<Window.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="16"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
<Style TargetType="Canvas">
<Setter Property="Height" Value="50"/>
<Setter Property="Width" Value="50"/>
<Setter Property="Margin" Value="8"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
</Style>
<Style TargetType="ComboBox">
<Setter Property="Width" Value="150"/>
<Setter Property="Margin" Value="8"/>
<Setter Property="DockPanel.Dock" Value="Top"/>
</Style>
</Window.Resources>
7 Note
The binding target property (in this example, the Background property) must be a
dependency property. For more information, see Data Binding Overview.
See also
Specify the Binding Source
How-to Topics
How to: Implement Binding Validation
Article • 05/07/2025
This example shows how to use an ErrorTemplate and a style trigger to provide visual feedback
to inform the user when an invalid value is entered, based on a custom validation rule.
Example
The text content of the TextBox in the following example is bound to the Age property (of type
int) of a binding source object named ods . The binding is set up to use a validation rule named
AgeRangeRule so that if the user enters non-numeric characters or a value that is smaller than
21 or greater than 130, a red exclamation mark appears next to the text box and a tool tip with
the error message appears when the user moves the mouse over the text box.
XAML
The following example shows the implementation of AgeRangeRule , which inherits from
ValidationRule and overrides the Validate method. The Int32.Parse method is called on the
value to make sure that it does not contain any invalid characters. The Validate method returns
a ValidationResult that indicates if the value is valid based on whether an exception is caught
during the parsing and whether the age value is outside of the lower and upper bounds.
C#
try
{
if (((string)value).Length > 0)
age = int.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, $"Illegal characters or
{e.Message}");
}
The following example shows the custom ControlTemplate validationTemplate that creates a
red exclamation mark to notify the user of a validation error. Control templates are used to
redefine the appearance of a control.
XAML
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="20">!</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
As shown in the following example, the ToolTip that shows the error message is created using
the style named textBoxInError . If the value of HasError is true , the trigger sets the tool tip of
the current TextBox to its first validation error. The RelativeSource is set to Self, referring to the
current element.
XAML
Data object
The following snippet is the data object used in the previous code examples. An instance is
created in the XAML as a static resource with the key of ods :
C#
Complete example
For the complete example, see Bind Validation sample .
Note that if you do not provide a custom ErrorTemplate the default error template appears to
provide visual feedback to the user when there is a validation error. See "Data Validation" in
Data Binding Overview for more information. Also, WPF provides a built-in validation rule that
catches exceptions that are thrown during the update of the binding source property. For more
information, see ExceptionValidationRule.
See also
Data Binding Overview
How-to Topics
How to: Implement Validation Logic on
Custom Objects
Article • 05/07/2025
This example shows how to implement validation logic on a custom object and then bind to it.
Example
You can provide validation logic on the business layer if your source object implements
IDataErrorInfo, as in the following example, which defines a Person object that implements
IDataErrorInfo:
C#
if (name == "Age")
{
if (this.age < 0 || this.age > 150)
{
result = "Age must not be less than 0 or greater than 150.";
}
}
return result;
}
}
}
In the following example, the text property of the text box binds to the Person.Age property,
which has been made available for binding through a resource declaration that is given the
x:Key data . The DataErrorValidationRule checks for the validation errors raised by the
IDataErrorInfo implementation.
XAML
<Window x:Class="BusinessLayerValidation.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF IDataErrorInfo Sample" Width="350" Height="150"
xmlns:src="clr-namespace:BusinessLayerValidation">
<Window.Resources>
<src:Person x:Key="data"/>
<!--The tool tip for the TextBox to display the validation error message.-
->
<Style x:Key="textBoxInError" TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static
RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel Margin="20">
<TextBlock>Enter your age:</TextBlock>
<TextBox Style="{StaticResource textBoxInError}">
<TextBox.Text>
<!--By setting ValidatesOnExceptions to True, it checks for
exceptions
that are thrown during the update of the source property.
An alternative syntax is to add <ExceptionValidationRule/> within
the <Binding.ValidationRules> section.-->
<Binding Path="Age" Source="{StaticResource data}"
ValidatesOnExceptions="True"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<!--DataErrorValidationRule checks for validation
errors raised by the IDataErrorInfo object.-->
<!--Alternatively, you can set
ValidationOnDataErrors="True" on the Binding.-->
<DataErrorValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
See also
ExceptionValidationRule
Implement Binding Validation
How-to Topics
How to: Get the Binding Object from a
Bound Target Property
Article • 05/07/2025
This example shows how to obtain the binding object from a data-bound target property.
Example
You can do the following to get the Binding object:
C#
7 Note
You must specify the dependency property for the binding you want because it is possible
that more than one property of the target object is using data binding.
Alternatively, you can get the BindingExpression and then get the value of the ParentBinding
property.
7 Note
See also
Create a Binding in Code
How-to Topics
How to: Implement a CompositeCollection
Article • 05/07/2025
Example
The following example shows how to display multiple collections and items as one list using
the CompositeCollection class. In this example, GreekGods is an ObservableCollection<T> of
GreekGod custom objects. Data templates are defined so that GreekGod objects and GreekHero
XAML
<Window Background="Cornsilk"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample"
x:Class="SDKSample.Window1"
Title="CompositeCollections"
SizeToContent="WidthAndHeight"
>
<Window.Resources>
<c:GreekGods x:Key="GreekGodsData"/>
<StackPanel>
<TextBlock FontSize="18" FontWeight="Bold" Margin="10"
HorizontalAlignment="Center">Composite Collections Sample</TextBlock>
<ListBox Name="myListBox" Height="300" Width="200" Background="White">
<ListBox.ItemsSource>
<CompositeCollection>
<CollectionContainer
Collection="{Binding Source={StaticResource GreekGodsData}}" />
<CollectionContainer
Collection="{Binding Source={StaticResource GreekHeroesData}}" />
<ListBoxItem Foreground="Red">Other Listbox Item 1</ListBoxItem>
<ListBoxItem Foreground="Red">Other Listbox Item 2</ListBoxItem>
</CompositeCollection>
</ListBox.ItemsSource>
</ListBox>
</StackPanel>
</Window>
See also
CollectionContainer
ItemsSource
XmlDataProvider
DataTemplate
Data Binding Overview
How-to Topics
How to: Convert Bound Data
Article • 05/07/2025
This example shows how to apply conversion to data that is used in bindings.
To convert data during binding, you must create a class that implements the IValueConverter
interface, which includes the Convert and ConvertBack methods.
Example
The following example shows the implementation of a date converter that converts the date
value passed in so that it only shows the year, the month, and the day. When implementing the
IValueConverter interface, it is a good practice to decorate the implementation with a
ValueConversionAttribute attribute to indicate to development tools the data types involved in
the conversion, as in the following example:
C#
[ValueConversion(typeof(DateTime), typeof(String))]
public class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
DateTime date = (DateTime)value;
return date.ToShortDateString();
}
Once you have created a converter, you can add it as a resource in your Extensible Application
Markup Language (XAML) file. In the following example, src maps to the namespace in which
DateConverter is defined.
XAML
<src:DateConverter x:Key="dateConverter"/>
Finally, you can use the converter in your binding using the following syntax. In the following
example, the text content of the TextBlock is bound to StartDate, which is a property of an
external data source.
XAML
The style resources referenced in the above example are defined in a resource section not
shown in this topic.
See also
Implement Binding Validation
Data Binding Overview
How-to Topics
How to: Create a Binding in Code
Article • 05/07/2025
Example
The FrameworkElement class and the FrameworkContentElement class both expose a
SetBinding method. If you are binding an element that inherits either of these classes, you can
The following example creates a class named, MyData , which contains a property named
MyDataProperty .
C#
public MyData() { }
C#
Instead of calling SetBinding, you can use the SetBinding static method of the
BindingOperations class. The following example, calls BindingOperations.SetBinding instead of
FrameworkElement.SetBinding to bind myText to myDataProperty .
C#
See also
Data Binding Overview
How-to Topics
How to: Get the Default View of a Data
Collection
Article • 05/07/2025
Views allow the same data collection to be viewed in different ways, depending on sorting,
filtering, or grouping criteria. Every collection has one shared default view, which is used as the
actual binding source when a binding specifies a collection as its source. This example shows
how to get the default view of a collection.
Example
To create the view, you need an object reference to the collection. This data object can be
obtained by referencing your own code-behind object, by getting the data context, by getting
a property of the data source, or by getting a property of the binding. This example shows how
to get the DataContext of a data object and use it to directly obtain the default collection view
for this collection.
C#
myCollectionView = (CollectionView)
CollectionViewSource.GetDefaultView(rootElem.DataContext);
In this example, the root element is a StackPanel. The DataContext is set to myDataSource,
which refers to a data provider that is an ObservableCollection<T> of Order objects.
XAML
<StackPanel.DataContext>
<Binding Source="{StaticResource myDataSource}"/>
</StackPanel.DataContext>
Alternatively, you can instantiate and bind to your own collection view using the
CollectionViewSource class. This collection view is only shared by controls that bind to it
directly. For an example, see the How to Create a View section in the Data Binding Overview.
For examples of the functionality provided by a collection view, see Sort Data in a View, Filter
Data in a View, and Navigate Through the Objects in a Data CollectionView.
See also
Sort and Group Data Using a View in XAML
How-to Topics
How to: Navigate Through the Objects in a
Data CollectionView
Article • 05/07/2025
Views allow the same data collection to be viewed in different ways, depending on sorting,
filtering, or grouping. Views also provide a current record pointer concept and enable moving
the pointer. This example shows how to get the current object as well as navigate through the
objects in a data collection using the functionality provided in the CollectionView class.
Example
In this example, myCollectionView is a CollectionView object that is a view over a bound
collection.
In the following example, OnButton is an event handler for the Previous and Next buttons in
an application, which are buttons that allow the user to navigate the data collection. Note that
the IsCurrentBeforeFirst and IsCurrentAfterLast properties report whether the current record
pointer has come to the beginning and the end of the list respectively so that
MoveCurrentToFirst and MoveCurrentToLast can be called as appropriately.
The CurrentItem property of the view is cast as an Order to return the current order item in the
collection.
C#
switch (b.Name)
{
case "Previous":
myCollectionView.MoveCurrentToPrevious();
if (myCollectionView.IsCurrentBeforeFirst)
{
myCollectionView.MoveCurrentToLast();
}
break;
case "Next":
myCollectionView.MoveCurrentToNext();
if (myCollectionView.IsCurrentAfterLast)
{
myCollectionView.MoveCurrentToFirst();
}
break;
o = myCollectionView.CurrentItem as Order;
// TODO: do something with the current Order o
}
}
See also
Data Binding Overview
Sort Data in a View
Filter Data in a View
Sort and Group Data Using a View in XAML
How-to Topics
How to: Filter Data in a View
Article • 05/07/2025
Example
To create a filter, define a method that provides the filtering logic. The method is used as a
callback and accepts a parameter of type object . The following method returns all the Order
objects with the filled property set to "No", filtering out the rest of the objects.
C#
You can then apply the filter, as shown in the following example. In this example,
myCollectionView is a ListCollectionView object.
C#
C#
myCollectionView.Filter = null;
For information about how to create or obtain a view, see Get the Default View of a Data
Collection. For the complete example, see Sorting and Filtering Items in a View Sample .
If your view object comes from a CollectionViewSource object, you apply filtering logic by
setting an event handler for the Filter event. In the following example, listingDataView is an
instance of CollectionViewSource.
C#
C#
See also
CanFilter
CustomFilter
Data Binding Overview
Sort Data in a View
How-to Topics
How to: Sort Data in a View
Article • 05/07/2025
Example
The following example creates a simple ListBox and a Button:
XAML
<Window x:Class="ListBoxSort_snip.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ListBoxSort_snip" Height="300" Width="300">
<DockPanel>
<ListBox Name="myListBox" DockPanel.Dock="Top">
<ListBoxItem>my</ListBoxItem>
<!--Or you can set the content this way:-->
<!--<ListBoxItem Content="my"/>-->
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>Sort</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
<ListBoxItem>ListBox</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
</ListBox>
<Button Click="OnClick" Width="30" Height="20"
DockPanel.Dock="Top">Sort</Button>
</DockPanel>
</Window>
The Click event handler of the button contains logic to sort the items in the ListBox in the
descending order. You can do this because adding items to a ListBox this way adds them to the
ItemCollection of the ListBox, and ItemCollection derives from the CollectionView class. If you
are binding your ListBox to a collection using the ItemsSource property, you can use the same
technique to sort.
C#
As long as you have a reference to the view object, you can use the same technique to sort the
content of other collection views. For an example of how to obtain a view, see Get the Default
View of a Data Collection. For another example, see Sort a GridView Column When a Header Is
Clicked. For more information about views, see Binding to Collections in Data Binding
Overview.
For an example of how to apply sorting logic in Extensible Application Markup Language
(XAML), see Sort and Group Data Using a View in XAML.
See also
CustomSort
Sort a GridView Column When a Header Is Clicked
Data Binding Overview
Filter Data in a View
How-to Topics
How to: Sort and Group Data Using a View
in XAML
Article • 05/07/2025
This example shows how to create a view of a data collection in Extensible Application Markup
Language (XAML). Views allow for the functionalities of grouping, sorting, filtering, and the
notion of a current item.
Example
In the following example, the static resource named places is defined as a collection of Place
objects, in which each Place object is consisted of a city name and the state. The prefix src is
mapped to the namespace where the data source Places is defined. The prefix scm maps to
"clr-namespace:System.ComponentModel;assembly=WindowsBase" and dat maps to "clr-
namespace:System.Windows.Data;assembly=PresentationFramework" .
The following example creates a view of the data collection that is sorted by the city name and
grouped by the state.
XAML
<Window.Resources>
<src:Places x:Key="places"/>
XAML
For bindings to XML data defined in an XmlDataProvider resource, precede the XML name with
an @ symbol.
XAML
XAML
<CollectionViewSource x:Key="mySortedTasks"
Source="{StaticResource myTasks}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="@Priority" />
</CollectionViewSource.SortDescriptions>
<CollectionViewSource.GroupDescriptions>
<dat:PropertyGroupDescription PropertyName="@Priority" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
See also
CollectionViewSource
Get the Default View of a Data Collection
Data Binding Overview
How-to Topics
How to: Use the Master-Detail Pattern with
Hierarchical Data
Article • 05/07/2025
Example
In this example, LeagueList is a collection of Leagues . Each League has a Name and a collection
of Divisions , and each Division has a name and a collection of Teams . Each Team has a team
name.
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:SDKSample"
Width="400" Height="180"
Title="Master-Detail Binding"
Background="Silver">
<Window.Resources>
<src:LeagueList x:Key="MyList"/>
XAML
<StackPanel>
<Label Content="{Binding Path=Name}"/>
<ListBox ItemsSource="{Binding Path=Divisions}" DisplayMemberPath="Name"
IsSynchronizedWithCurrentItem="true"/>
</StackPanel>
<StackPanel>
<Label Content="{Binding Path=Divisions/Name}"/>
<ListBox DisplayMemberPath="Name" ItemsSource="{Binding
Path=Divisions/Teams}"/>
</StackPanel>
</DockPanel>
</Window>
The following is a screenshot of the example. The Divisions ListBox automatically tracks
selections in the Leagues ListBox and display the corresponding data. The Teams ListBox tracks
selections in the other two ListBox controls.
1. The three ListBox controls bind to the same source. You set the Path property of the
binding to specify which level of data you want the ListBox to display.
The technique is slightly different when you are using XML data. For an example, see Use the
Master-Detail Pattern with Hierarchical XML Data.
See also
HierarchicalDataTemplate
Bind to a Collection and Display Information Based on Selection
Data Binding Overview
Data Templating Overview
How-to Topics
How to: Use the Master-Detail Pattern with
Hierarchical XML Data
Article • 05/07/2025
This example shows how to implement the master-detail scenario with XML data.
Example
This example is the XML data version of the example discussed in Use the Master-Detail
Pattern with Hierarchical Data. In this example, the data is from the file League.xml . Note how
the third ListBox control tracks selection changes in the second ListBox by binding to its
SelectedValue property.
XAML
<Window x:Class="SDKSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Multiple ListBox Binding Sample"
Width="400" Height="200"
Background="Cornsilk">
<Window.Resources>
<XmlDataProvider x:Key="MyList" Source="Data\Leagues.xml"
XPath="Leagues/League"/>
<DataTemplate x:Key="dataTemplate">
<TextBlock Text="{Binding XPath=@name}" />
</DataTemplate>
XAML
</Window.Resources>
<StackPanel>
<Label Content="{Binding XPath=@name}"/>
<ListBox Name="divisionsListBox"
ItemsSource="{Binding XPath=Division}"
ItemTemplate="{StaticResource dataTemplate}"
IsSynchronizedWithCurrentItem="true"/>
</StackPanel>
<StackPanel>
<Label Content="{Binding XPath=@name}"/>
<ListBox DataContext="{Binding ElementName=divisionsListBox,
Path=SelectedItem}"
ItemsSource="{Binding XPath=Team}"
ItemTemplate="{StaticResource dataTemplate}"/>
</StackPanel>
</DockPanel>
</Window>
See also
HierarchicalDataTemplate
How-to Topics
How to: Produce a Value Based on a List of
Bound Items
Article • 05/07/2025
MultiBinding allows you to bind a binding target property to a list of source properties and
then apply logic to produce a value with the given inputs. This example demonstrates how to
use MultiBinding.
Example
In the following example, NameListData refers to a collection of PersonName objects, which are
objects that contain two properties, firstName and lastName . The following example produces
a TextBlock that shows the first and last names of a person with the last name first.
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample"
x:Class="SDKSample.Window1"
Width="400"
Height="280"
Title="MultiBinding Sample">
<Window.Resources>
<c:NameList x:Key="NameListData"/>
<c:NameConverter x:Key="myNameConverter"/>
XAML
</Window.Resources>
XAML
</Window>
To understand how the last-name-first format is produced, let's take a look at the
implementation of the NameConverter :
C#
switch ((string)parameter)
{
case "FormatLastFirst":
name = values[1] + ", " + values[0];
break;
case "FormatNormal":
default:
name = values[0] + " " + values[1];
break;
}
return name;
}
from the individual bindings and stores them in the values object array. The order in which the
Binding elements appear under the MultiBinding element is the order in which those values are
stored in the array. The value of the ConverterParameter attribute is referenced by the
parameter argument of the Converter method, which performs a switch on the parameter to
determine how to format the name.
See also
Convert Bound Data
Data Binding Overview
How-to Topics
How to: Implement Property Change
Notification
Article • 05/07/2025
Example
To implement INotifyPropertyChanged you need to declare the PropertyChanged event and
create the OnPropertyChanged method. Then for each property you want change notifications
for, you call OnPropertyChanged whenever the property is updated.
C#
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace SDKSample
{
// This class implements INotifyPropertyChanged
// to support one-way and two-way bindings
// (such that the UI element updates when the source
// has been changed dynamically)
public class Person : INotifyPropertyChanged
{
private string name;
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
public Person()
{
}
To see an example of how the Person class can be used to support TwoWay binding, see
Control When the TextBox Text Updates the Source.
See also
Binding Sources Overview
Data Binding Overview
How-to Topics
How to: Create and Bind to an
ObservableCollection
Article • 05/07/2025
This example shows how to create and bind to a collection that derives from the
ObservableCollection<T> class, which is a collection class that provides notifications when
items get added or removed.
Example
The following example shows the implementation of a NameList collection:
C#
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:SDKSample"
x:Class="SDKSample.Window1"
Width="400"
Height="280"
Title="MultiBinding Sample">
<Window.Resources>
<c:NameList x:Key="NameListData"/>
...
</Window.Resources>
XAML
<ListBox Width="200"
ItemsSource="{Binding Source={StaticResource NameListData}}"
ItemTemplate="{StaticResource NameItemTemplate}"
IsSynchronizedWithCurrentItem="True"/>
7 Note
The objects in your collection must satisfy the requirements described in the Binding
Sources Overview. In particular, if you are using OneWay or TwoWay (for example, you
want your UI to update when the source properties change dynamically), you must
implement a suitable property changed notification mechanism such as the
INotifyPropertyChanged interface.
For more information, see the Binding to Collections section in the Data Binding Overview.
See also
Sort Data in a View
Filter Data in a View
Sort and Group Data Using a View in XAML
Data Binding Overview
How-to Topics
How to: Implement PriorityBinding
Article • 05/07/2025
Example
To demonstrate how PriorityBinding works, the AsyncDataSource object has been created with
the following three properties: FastDP , SlowerDP , and SlowestDP .
The get accessor of FastDP returns the value of the _fastDP data member.
The get accessor of SlowerDP waits for 3 seconds before returning the value of the _slowerDP
data member.
The get accessor of SlowestDP waits for 5 seconds before returning the value of the
_slowestDP data member.
7 Note
This example is for demonstration purposes only. The .NET guidelines recommend against
defining properties that are orders of magnitude slower than a field set would be. For
more information, see Choosing Between Properties and Methods.
C#
public AsyncDataSource()
{
}
XAML
<Window.Resources>
<c:AsyncDataSource SlowestDP="Slowest Value" SlowerDP="Slower Value"
FastDP="Fast Value" x:Key="AsyncDS" />
</Window.Resources>
After 3 seconds elapses, the SlowerDP property returns the value "Slower Value". The TextBlock
then displays the value "Slower Value".
After 5 seconds elapses, the SlowestDP property returns the value "Slowest Value". That
binding has the highest priority because it is listed first. The TextBlock now displays the value
"Slowest Value".
See PriorityBinding for information about what is considered a successful return value from a
binding.
See also
Binding.IsAsync
Data Binding Overview
How-to Topics
How to: Bind to XML Data Using an
XMLDataProvider and XPath Queries
Article • 05/07/2025
With an XmlDataProvider, the underlying data that can be accessed through data binding in
your application can be any tree of XML nodes. In other words, an XmlDataProvider provides a
convenient way to use any tree of XML nodes as a binding source.
Example
In the following example, the data is embedded directly as an XML data island within the
Resources section. An XML data island must be wrapped in <x:XData> tags and always have a
single root node, which is Inventory in this example.
7 Note
The root node of the XML data has an xmlns attribute that sets the XML namespace to an
empty string. This is a requirement for applying XPath queries to a data island that is inline
within the XAML page. In this inline case, the XAML, and thus the data island, inherits the
System.Windows namespace. Because of this, you need to set the namespace blank to
keep XPath queries from being qualified by the System.Windows namespace, which
would misdirect the queries.
XAML
<StackPanel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Cornsilk">
<StackPanel.Resources>
<XmlDataProvider x:Key="InventoryData" XPath="Inventory/Books">
<x:XData>
<Inventory xmlns="">
<Books>
<Book ISBN="0-7356-0562-9" Stock="in" Number="9">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
</Book>
<Book ISBN="0-7356-1370-2" Stock="in" Number="8">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
</Book>
<Book ISBN="0-7356-1288-9" Stock="out" Number="7">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
</Book>
<Book ISBN="0-7356-1377-X" Stock="in" Number="5">
<Title>Introducing Microsoft .NET</Title>
<Summary>Overview of .NET Technology</Summary>
</Book>
<Book ISBN="0-7356-1448-2" Stock="out" Number="4">
<Title>Microsoft C# Language Specifications</Title>
<Summary>The C# language definition</Summary>
</Book>
</Books>
<CDs>
<CD Stock="in" Number="3">
<Title>Classical Collection</Title>
<Summary>Classical Music</Summary>
</CD>
<CD Stock="out" Number="9">
<Title>Jazz Collection</Title>
<Summary>Jazz Music</Summary>
</CD>
</CDs>
</Inventory>
</x:XData>
</XmlDataProvider>
</StackPanel.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="12" Foreground="Red">
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
As shown in this example, to create the same binding declaration in attribute syntax you must
escape the special characters properly. For more information, see XML Character Entities and
XAML.
The ListBox will show the following items when this example is run. These are the Titles of all of
the elements under Books with either a Stock value of "out" or a Number value of 3 or greater
than or equals to 8. Notice that no CD items are returned because the XPath value set on the
XmlDataProvider indicates that only the Books elements should be exposed (essentially setting
a filter).
In this example, the book titles are displayed because the XPath of the TextBlock binding in the
DataTemplate is set to "Title". If you want to display the value of an attribute, such as the ISBN,
you would set that XPath value to " @ISBN ".
The XPath properties in WPF are handled by the XmlNode.SelectNodes method. You can
modify the XPath queries to get different results. Here are some examples for the XPath query
on the bound ListBox from the previous example:
XPath="Book[1]" will return the first book element ("XML in Action"). Note that XPath
Microsoft .NET").
XPath="*[position()>3]" will return all of the book elements except for the first 3.
When you run an XPath query, it returns an XmlNode or a list of XmlNodes. XmlNode is a
common language runtime (CLR) object, which means you can use the Path property to bind to
the common language runtime (CLR) properties. Consider the previous example again. If the
rest of the example stays the same and you change the TextBlock binding to the following, you
will see the names of the returned XmlNodes in the ListBox. In this case, the name of all the
returned nodes is "Book".
XAML
In some applications, embedding the XML as a data island within the source of the XAML page
can be inconvenient because the exact content of the data must be known at compile time.
Therefore, obtaining the data from an external XML file is also supported, as in the following
example:
XAML
If the XML data resides in a remote XML file, you would define access to the data by assigning
an appropriate URL to the Source attribute as follows:
XML
See also
ObjectDataProvider
Bind to XDocument, XElement, or LINQ for XML Query Results
Use the Master-Detail Pattern with Hierarchical XML Data
Binding Sources Overview
Data Binding Overview
How-to Topics
How to: Bind to XDocument, XElement, or
LINQ for XML Query Results
Article • 05/07/2025
This example demonstrates how to bind XML data to an ItemsControl using XDocument.
Example
The following XAML code defines an ItemsControl and includes a data template for data of
type Planet in the http://planetsNS XML namespace. An XML data type that occupies a
namespace must include the namespace in braces, and if it appears where a XAML markup
extension could appear, it must precede the namespace with a brace escape sequence. This
code binds to dynamic properties that correspond to the Element and Attribute methods of
the XElement class. Dynamic properties enable XAML to bind to dynamic properties that share
the names of methods. To learn more, see LINQ to XML dynamic properties. Notice how the
default namespace declaration for the XML does not apply to attribute names.
XAML
<StackPanel Name="stacky">
<StackPanel.Resources>
<DataTemplate DataType="{}{http://planetsNS}Planet" >
<StackPanel Orientation="Horizontal">
<TextBlock Width="100" Text="{Binding
Path=Element[{http://planetsNS}DiameterKM].Value}" />
<TextBlock Width="100" Text="{Binding Path=Attribute[Name].Value}" />
<TextBlock Text="{Binding Path=Element[{http://planetsNS}Details].Value}"
/>
</StackPanel>
</DataTemplate>
</StackPanel.Resources>
XAML
<ItemsControl
ItemsSource="{Binding }" >
</ItemsControl>
</StackPanel>
The following C# code calls Load and sets the stack panel data context to all subelements of
the element named SolarSystemPlanets in the http://planetsNS XML namespace.
C#
planetsDoc = XDocument.Load("../../Planets.xml");
stacky.DataContext = planetsDoc.Element("
{http://planetsNS}SolarSystemPlanets").Elements();
XML data can be stored as a XAML resource using ObjectDataProvider. For a complete
example, see L2DBForm.xaml source code. The following sample shows how code can set the
data context to an object resource.
C#
planetsDoc = (XDocument)((ObjectDataProvider)Resources["justTwoPlanets"]).Data;
stacky.DataContext = planetsDoc.Element("
{http://planetsNS}SolarSystemPlanets").Elements();
The dynamic properties that map to Element and Attribute provide flexibility within XAML. Your
code can also bind to the results of a LINQ for XML query. This example binds to query results
ordered by an element value.
C#
stacky.DataContext =
from c in planetsDoc.Element("{http://planetsNS}SolarSystemPlanets").Elements()
orderby Int32.Parse(c.Element("{http://planetsNS}DiameterKM").Value)
select c;
See also
Binding Sources Overview
WPF Data Binding with LINQ to XML Overview
WPF Data Binding Using LINQ to XML Example
LINQ to XML Dynamic Properties
How to: Bind to the Results of a LINQ
Query
Article • 05/07/2025
This example demonstrates how to run a LINQ query and then bind to the results.
Example
The following example creates two list boxes. The first list box contains three list items.
XAML
<ListBox SelectionChanged="ListBox_SelectionChanged"
SelectedIndex="0" Margin="10,0,10,0" >
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
</ListBox>
<ListBox Width="400" Margin="10" Name="myListBox"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource myTaskTemplate}"/>
Selecting an item from the first list box invokes the following event handler. In this example,
Tasks is a collection of Task objects. The Task class has a property named Priority . This
event handler runs a LINQ query that returns the collection of Task objects that have the
selected priority value, and then sets that as the DataContext:
C#
using System.Linq;
C#
C#
The second list box binds to that collection because its ItemsSource value is set to {Binding} .
As a result, it displays the returned collection (based on the myTaskTemplate DataTemplate).
See also
Make Data Available for Binding in XAML
Bind to a Collection and Display Information Based on Selection
What's New in WPF Version 4.5
Data Binding Overview
How to: Use XML Namespaces in Data
Binding
Article • 05/07/2025
Example
This example shows how to handle namespaces specified in your XML binding source.
You can use the XmlNamespaceMapping element to map the namespace to a Prefix, as in the
following example. You can then use the Prefix to refer to the XML namespace. The ListBox in
this example displays the title and dc:date of each item.
XAML
<StackPanel.Resources>
<XmlNamespaceMappingCollection x:Key="mapping">
<XmlNamespaceMapping Uri="http://purl.org/dc/elements/1.1/" Prefix="dc" />
</XmlNamespaceMappingCollection>
<XmlDataProvider Source="http://msdn.microsoft.com/subscriptions/rss.xml"
XmlNamespaceManager="{StaticResource mapping}"
XPath="rss/channel/item" x:Key="provider"/>
<DataTemplate x:Key="dataTemplate">
<Border BorderThickness="1" BorderBrush="Gray">
<Grid Width="600" Height="50">
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding XPath=title}" />
<TextBlock Grid.Row="1" Text="{Binding XPath=dc:date}" />
</Grid>
</Border>
</DataTemplate>
</StackPanel.Resources>
<ListBox
Width="600"
Height="600"
Background="Honeydew"
ItemsSource="{Binding Source={StaticResource provider}}"
ItemTemplate="{StaticResource dataTemplate}"/>
Note that the Prefix you specify does not have to match the one used in the XML source; if the
prefix changes in the XML source your mapping still works.
In this particular example, the XML data comes from a web service, but the
XmlNamespaceMapping element also works with inline XML or XML data in an embedded file.
See also
Bind to XML Data Using an XMLDataProvider and XPath Queries
Data Binding Overview
How-to Topics
How to: Bind to an ADO.NET Data Source
Article • 05/07/2025
This example shows how to bind a Windows Presentation Foundation (WPF) ListBox control to
an ADO.NET DataSet .
Example
In this example, an OleDbConnection object is used to connect to the data source which is an
Access MDB file that is specified in the connection string. After the connection is established, an
OleDbDataAdapter object is created. The OleDbDataAdapter object executes a select Structured
Query Language (SQL) statement to retrieve the recordset from the database. The results from
the SQL command are stored in a DataTable of the DataSet by calling the Fill method of the
OleDbDataAdapter . The DataTable in this example is named BookTable . The example then sets
C#
DataSet myDataSet;
We can then bind the ItemsSource property of the ListBox to BookTable of the DataSet :
XAML
XAML
<StackPanel.Resources>
<c:IntColorConverter x:Key="MyConverter"/>
<DataTemplate x:Key="BookItemTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=Title}" Grid.Column="0"
FontWeight="Bold" />
<TextBlock Text="{Binding Path=ISBN}" Grid.Column="1" />
<TextBlock Grid.Column="2" Text="{Binding Path=NumPages}"
Background="{Binding Path=NumPages,
Converter={StaticResource MyConverter}}"/>
</Grid>
</DataTemplate>
</StackPanel.Resources>
The IntColorConverter converts an int to a color. With the use of this converter, the
Background color of the third TextBlock appears green if the value of NumPages is less than 350
and red otherwise. The implementation of the converter is not shown here.
See also
BindingListCollectionView
Data Binding Overview
How-to Topics
How to: Bind to a Method
Article • 05/07/2025
Example
In this example, TemperatureScale is a class that has a method ConvertTemp , which takes two
parameters (one of double and one of the enum type TempType) and converts the given value
from one temperature scale to another. In the following example, an ObjectDataProvider is
used to instantiate the TemperatureScale object. The ConvertTemp method is called with two
specified parameters.
XAML
<Window.Resources>
<ObjectDataProvider ObjectType="{x:Type local:TemperatureScale}"
MethodName="ConvertTemp" x:Key="convertTemp">
<ObjectDataProvider.MethodParameters>
<system:Double>0</system:Double>
<local:TempType>Celsius</local:TempType>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
Now that the method is available as a resource, you can bind to its results. In the following
example, the Text property of the TextBox and the SelectedValue of the ComboBox are bound
to the two parameters of the method. This allows users to specify the temperature to convert
and the temperature scale to convert from. Note that BindsDirectlyToSource is set to true
because we are binding to the MethodParameters property of the ObjectDataProvider instance
and not properties of the object wrapped by the ObjectDataProvider (the TemperatureScale
object).
The Content of the last Label updates when the user modifies the content of the TextBox or the
selection of the ComboBox.
XAML
The converter DoubleToString takes a double and turns it into a string in the Convert direction
(from the binding source to binding target, which is the Text property) and converts a string
to a double in the ConvertBack direction.
The InvalidCharacterRule is a ValidationRule that checks for invalid characters. The default
error template, which is a red border around the TextBox, appears to notify users when the
input value is not a double value.
See also
How-to Topics
Bind to an Enumeration
How to: Set Up Notification of Binding
Updates
Article • 05/07/2025
This example shows how to set up to be notified when the binding target (target) or the
binding source (source) property of a binding has been updated.
Example
Windows Presentation Foundation (WPF) raises a data update event each time that the binding
source or target has been updated. Internally, this event is used to inform the user interface
(UI) that it should update, because the bound data has changed. Note that for these events to
work, and also for one-way or two-way binding to work properly, you need to implement your
data class using the INotifyPropertyChanged interface. For more information, see Implement
Property Change Notification.
Here is an example that shows how to set up for notification when a target property has been
updated.
XAML
You can then assign a handler based on the EventHandler<T> delegate, OnTargetUpdated in
this example, to handle the event:
C#
Parameters of the event can be used to determine details about the property that changed
(such as the type or the specific element if the same handler is attached to more than one
element), which can be useful if there are multiple bound properties on a single element.
See also
Data Binding Overview
How-to Topics
How to: Clear Bindings
Article • 05/07/2025
Example
To clear a binding from an individual property on an object, call ClearBinding as shown in the
following example. The following example removes the binding from the TextProperty of
mytext, a TextBlock object.
C#
BindingOperations.ClearBinding(myText, TextBlock.TextProperty);
Clearing the binding removes the binding so that the value of the dependency property is
changed to whatever it would have been without the binding. This value could be a default
value, an inherited value, or a value from a data template binding.
See also
BindingOperations
Data Binding Overview
How-to Topics
How to: Find DataTemplate-Generated
Elements
Article • 05/07/2025
This example shows how to find elements that are generated by a DataTemplate.
Example
In this example, there is a ListBox that is bound to some XML data:
XAML
XAML
<DataTemplate x:Key="myDataTemplate">
<TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
If you want to retrieve the TextBlock element generated by the DataTemplate of a certain
ListBoxItem, you need to get the ListBoxItem, find the ContentPresenter within that
ListBoxItem, and then call FindName on the DataTemplate that is set on that ContentPresenter.
The following example shows how to perform those steps. For demonstration purposes, this
example creates a message box that shows the text content of the DataTemplate-generated
text block.
C#
C#
See also
How to: Find ControlTemplate-Generated Elements
Data Binding Overview
How-to Topics
Styling and Templating
WPF XAML Namescopes
Trees in WPF
Overview of WPF data binding with LINQ
to XML
Article • 05/07/2025
This article introduces the dynamic data binding features in the System.Xml.Linq namespace.
These features can be used as a data source for user interface (UI) elements in Windows
Presentation Foundation (WPF) apps. This scenario relies upon special dynamic properties of
System.Xml.Linq.XAttribute and System.Xml.Linq.XElement.
There are two broad ways that XAML and LINQ to XML can interact:
Because XAML files are well-formed XML, they can be queried and manipulated through
XML technologies such as LINQ to XML.
Because LINQ to XML queries represent a source of data, these queries can be used as a
data source for data binding for WPF UI elements.
ノ Expand table
Component Description
Binding The UI element to be associated with the data source. Visual elements in WPF are derived
target from the UIElement class.
Component Description
Target The dependency property of the binding target that reflects the value of the data-binding
property source. Dependency properties are directly supported by the DependencyObject class,
which UIElement derives from.
Binding The source object for one or more values that are supplied to the UI element for
source presentation. WPF automatically supports the following types as binding sources: CLR
objects, ADO.NET data objects, XML data (from XPath or LINQ to XML queries), or another
DependencyObject.
Source path The property of the binding source that resolves to the value or set of values that is to be
bound.
One-way binding causes the changes to one side to be propagated automatically. Most
commonly, changes to the source are reflected in the target, but the reverse can
sometimes be useful.
In two-way binding, changes to the source are automatically propagated to the target,
and changes to the target are automatically propagated to the source.
For one-way or two-way binding to occur, the source must implement a change notification
mechanism, for example by implementing the INotifyPropertyChanged interface or by using a
PropertyNameChanged pattern for each property supported.
For more information about data binding in WPF, see Data Binding (WPF).
These dynamic properties are special run-time properties that duplicate the functionality of
existing methods and properties in the XAttribute and XElement classes. They were added to
these classes solely to enable them to act as dynamic data sources for WPF. To meet this need,
all these dynamic properties implement change notifications. A detailed reference for these
dynamic properties is provided in the next section, LINQ to XML Dynamic Properties.
7 Note
Many of the standard public properties, found in the various classes in the
System.Xml.Linq namespace, can be used for one-time data binding. However, remember
that neither the source nor the target will be dynamically updated under this scheme.
Accessed directly at compile time. Dynamic properties are invisible to the compiler and to
Visual Studio IntelliSense.
Discovered or accessed at run time using .NET reflection. Even at run time, they are not
properties in the basic CLR sense.
In C#, dynamic properties can only be accessed at run time through facilities provided by the
System.ComponentModel namespace.
XML
<object>.<dynamic-property>
The dynamic properties for these two classes either resolve to a value that can be used directly,
or to an indexer that must be supplied with an index to obtain the resulting value or collection
of values. The latter syntax takes the form:
XML
<object>.<dynamic-property>[<index-value>]
To implement WPF dynamic binding, dynamic properties will be used with facilities provided by
the System.Windows.Data namespace, most notably the Binding class.
See also
WPF Data Binding with LINQ to XML
LINQ to XML Dynamic Properties
XAML in WPF
Data Binding (WPF)
Using Workflow Markup
LINQ to XML dynamic properties
Article • 05/07/2025
This section provides reference information about the dynamic properties in LINQ to XML.
Specifically, these properties are exposed by the XAttribute and XElement classes, which are in
the System.Xml.Linq namespace.
As explained in the topic Overview of WPF data binding with LINQ to XML, each of the
dynamic properties is equivalent to a standard public property or method in the same class.
These standard members should be used for most purposes; dynamic properties are provided
specifically for LINQ to XML data binding scenarios. For more information about the standard
members of these classes, see the XAttribute and XElement reference topics.
With respect to their resolved values, the dynamic properties in this section fall into two
categories:
Simple ones, such as the Value properties in the XAttribute and XElement classes, that
resolve to a single value.
Indexed values, such as the Elements and Descendants properties of XElement, that
resolve into an indexer type. For indexer types to be resolved to the desired value or
collection, an expanded name parameter must be passed to them.
All the dynamic properties that return an indexed value of type IEnumerable<T> use deferred
execution. For more information about deferred execution, see Introduction to LINQ queries
(C#).
Reference
System.Xml.Linq
System.Xml.Linq.XElement
System.Xml.Linq.XAttribute
See also
WPF data binding with LINQ to XML
WPF data binding with LINQ to XML overview
Introduction to LINQ queries (C#)
Value (XAttribute dynamic property)
Article • 05/07/2025
Syntax
XAML
attrib.Value
Exceptions
ノ Expand table
Remarks
This property is equivalent to the Value property of the System.Xml.Linq.XAttribute class, but
this dynamic property also supports change notifications.
See also
System.Xml.Linq.XAttribute.Value
XAttribute class dynamic properties
Attribute
Attribute (XElement dynamic property)
Article • 05/07/2025
Gets an indexer used to retrieve the attribute instance that corresponds to the specified
expanded name.
Syntax
XAML
elem.Attribute[{namespaceName}attribName]
Remarks
This property is equivalent to the Attribute method of the System.Xml.Linq.XElement class.
See also
System.Xml.Linq.XElement.Attribute
XElement Class Dynamic Properties
Value
Element (XElement dynamic property)
Article • 05/07/2025
Gets an indexer used to retrieve the child element instance that corresponds to the specified
expanded name.
Syntax
XAML
elem.Element[{namespaceName}localName]
Remarks
This property is equivalent to Element method of the System.Xml.Linq.XContainer class.
See also
System.Xml.Linq.XContainer.Element
XElement class dynamic properties
Elements
Elements (XElement dynamic property)
Article • 05/07/2025
Gets an indexer used to retrieve the child elements of the current element that match the
specified expanded name.
Syntax
XAML
elem.Elements[{namespaceName}localName]
Remarks
This property is equivalent to the System.Xml.Linq.XContainer.Elements(XName) method of the
XContainer class.
The elements in the returned collection are in XML source document order.
See also
XElement class dynamic properties
Element
Descendants
Descendants (XElement dynamic property)
Article • 05/07/2025
Gets an indexer used to retrieve all the descendant elements of the current element that match
the specified expanded name.
Syntax
XAML
elem.Descendants[{namespaceName}localName]
Remarks
This property is equivalent to the System.Xml.Linq.XContainer.Descendants(XName) method of
the XContainer class.
The elements in the returned collection are in XML source document order.
See also
XElement class dynamic properties
Elements
Value (XElement dynamic property)
Article • 05/07/2025
Syntax
XAML
elem.Value
Remarks
This property is equivalent to the Value property of the System.Xml.Linq.XElement class, but
this dynamic property also supports change notifications.
See also
System.Xml.Linq.XElement.Value
XElement class dynamic properties
Xml
Xml (XElement dynamic property)
Article • 05/07/2025
Syntax
XAML
elem.Xml
Remarks
This property is equivalent to the ToString(SaveOptions) method of the System.Xml.Linq.XNode
class, with the SaveOptions parameter set to SaveOptions.
See also
XElement class dynamic properties
Value
LINQ to XML data binding sample
Article • 05/07/2025
Overview
The LinqToXmlDataBinding sample is a Windows Presentation Foundation (WPF) app that
contains C# and XAML source files. An embedded XML document defines a list of books. The
app enables the user to view, add, delete, and edit the book entries.
L2DBForm.xaml contains the XAML declaration code for the user interface (UI) of the
main window. It also contains a window resource section that defines a data provider and
an embedded XML document for the book listings.
The main window is divided into the following four vertical UI sections:
XML displays the raw XML source of the embedded book listing.
Book List displays the book entries as standard text and enables the user to select and
delete individual entries.
Edit Selected Book enables the user to edit the values associated with the currently
selected book entry.
Add New Book enables the creation of a new book entry based on values entered by the
user.
2. If not already present, add project references for the following .NET assemblies:
System.Data
System.Data.DataSetExtensions
System.Xml
System.Xml
The project should compile without errors and run as a generic WPF application.
Add code
1. In Solution Explorer, rename the source file Window1.xaml to L2XDBForm.xaml.
2. Replace the source code found in the file L2XDBForm.xaml with the L2DBForm.xaml
source code. Use the XAML source view to work with this file.
4. In the file App.xaml, replace all occurrences of the string Window1.xaml with
L2XDBForm.xaml.
A program window with the title WPF Data Binding using LINQ to XML appears.
The top section of the UI displays the raw XML that represents the book list. It is displayed
using a WPF TextBlock control, which does not enable interaction through the mouse or
keyboard.
The second vertical section, labeled Book List, displays the books as a plain text ordered list. It
uses a ListBox control that enables selection though the mouse or keyboard.
Add and delete books
To add a new book to the list, enter values into the ID and Value TextBox controls in the last
section, Add New Book, and then select Add Book. The book is appended to the list in both
the book and XML listings. This program does not validate input values.
To delete an existing book from the list, select it in the Book List section, and then select
Remove Selected Book. The book entry is removed from both the book and the raw XML
source listings.
Its current values are displayed in the Edit Selected Book section.
2. Edit the values using the keyboard. As soon as either TextBox control loses focus, changes
are automatically propagated to the XML source and book listings.
L2DBForm.xaml source code
Article • 05/07/2025
This page contains and describes the XAML source file for the WPF data binding using LINQ to
XML example.
Overall UI structure
As is typical for a WPF project, this file contains one parent element, a Window XML element
that's associated with the derived class L2XDBFrom in the LinqToXmlDataBinding namespace.
The client area is contained within a StackPanel that's given a light blue background. This panel
contains four DockPanel UI sections separated by Separator bars. The purpose of these
sections is described here.
Each section contains a label that identifies it. In the first two sections, this label is rotated 90
degrees through the use of a LayoutTransform. The rest of the section contains UI elements
appropriate to the purpose of that section, for example, text blocks, text boxes, and buttons.
Sometimes a child StackPanel is used to align these child controls.
The <ObjectDataProvider> tag, which spans lines 11 through 25, declares a ObjectDataProvider,
named LoadedBooks , that uses an XElement as the source. The XElement is initialized by parsing
an embedded XML document (a CDATA element). Notice that white space is preserved when
declaring the embedded XML document and also when it's parsed. White space is preserved
because the TextBlock control, which is used to display the raw XML, has no special XML
formatting capabilities.
Lastly, a DataTemplate named BookTemplate is defined on lines 28 through 34. This template is
used to display the entries in the Book List UI section. It uses data binding and LINQ to XML
dynamic properties to retrieve the book ID and book name through the following assignments:
XAML
In the opening <StackPanel> tag on line 38, the DataContext property of this panel is set to the
LoadedBooks data provider.
XAML
Setting the data context makes it possible (on line 46) for the TextBlock named tbRawXml to
display the raw XML by binding to this data provider's Xml property:
XAML
Text="{Binding Path=Xml}"
The ListBox in the Book List UI section, on lines 58 through 62, sets the template for its display
items to the BookTemplate defined in the window resource section:
XAML
Then, on lines 59 through 62, the actual values of the books are bound to this list box:
XAML
<ListBox.ItemsSource>
<Binding Path="Elements[{http://www.mybooks.com}book]"/>
</ListBox.ItemsSource>
The third UI section, Edit Selected Book, first binds the DataContext of the parent StackPanel
to the currently selected item in from the Book List UI section (line 82):
XAML
It then uses two-way data binding, so that the current values of the book elements are
displayed to, and updated from, the two text boxes in this panel. Data binding to dynamic
properties is similar to the data binding used in the BookTemplate data template:
XAML
The last UI section, Add New Book, doesn't use data binding in its XAML code. Instead, data
binding is in its event handling code in the file L2DBForm.xaml.cs.
Example
Description
7 Note
We recommend that you copy the following code below into a code editor, such as the C#
source code editor in Visual Studio, so that line numbers will be easier to track.
Code
XML
<Window x:Class="LinqToXmlDataBinding.L2XDBForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:xlinq="clr-namespace:System.Xml.Linq;assembly=System.Xml.Linq"
xmlns:local="clr-namespace:LinqToXmlDataBinding"
Title="WPF Data Binding using LINQ-to-XML" Height="665" Width="500"
ResizeMode="NoResize">
<Window.Resources>
<!-- Books provider and inline data -->
<ObjectDataProvider x:Key="LoadedBooks" ObjectType="{x:Type
xlinq:XElement}" MethodName="Parse">
<ObjectDataProvider.MethodParameters>
<system:String xml:space="preserve">
<![CDATA[
<books xmlns="http://www.mybooks.com">
<book id="0">book zero</book>
<book id="1">book one</book>
<book id="2">book two</book>
<book id="3">book three</book>
</books>
]]>
</system:String>
<xlinq:LoadOptions>PreserveWhitespace</xlinq:LoadOptions>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
Comments
For the C# source code for the event handlers associated with the WPF UI elements, see
L2DBForm.xaml.cs source code.
See also
Walkthrough: LinqToXmlDataBinding example
L2DBForm.xaml.cs source code
L2DBForm.xaml.cs source code
Article • 05/07/2025
This page contains the contents and description of the C# source code in the file
L2DBForm.xaml.cs. The L2XDBForm partial class contained in this file can be divided into three
logical sections: data members and the OnRemove and OnAddBook button click event handlers.
Data members
Two private data members are used to associate this class to the window resources used in
L2DBForm.xaml.
C#
bookList = (XElement)((ObjectDataProvider)Resources["LoadedBooks"]).Data;
The second statement creates a new XElement from the string values the user entered in
the Add New Book user interface (UI) section.
The last statement adds this new book element to the data provider in L2DBForm.xaml.
Consequently, dynamic data binding will automatically update the UI with this new item;
no extra user-supplied code is required.
First, the book element associated with the currently selected item in the list box is
retrieved:
C#
C#
selBook.Remove();
Again, dynamic data binding assures that the program's UI is automatically updated.
Example
Code
C#
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Xml;
using System.Xml.Linq;
namespace LinqToXmlDataBinding {
/// <summary>
/// Interaction logic for L2XDBForm.xaml
/// </summary>
Comments
For the associated XAML source for these handlers, see L2DBForm.xaml source code.
See also
Walkthrough: LinqToXmlDataBinding example
L2DBForm.xaml source code