Data Binding Overview - WPF .NET - Microsoft Learn
Data Binding Overview - WPF .NET - Microsoft Learn
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.
) Important
The Desktop Guide documentation for .NET 7 and .NET 6 is under construction.
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.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 1/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
As the figure shows, data binding is essentially the bridge between your binding target and
your binding source. The figure demonstrates the following fundamental WPF data binding
concepts:
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
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.
As indicated by the arrow in the previous figure, the data flow of a binding can go from the
binding target to the binding source (for example, the source value changes when a user
edits the value of a TextBox ) and/or from the binding source to the binding target (for
example, your TextBox content is updated with changes in the binding source) if the
binding source provides the proper notifications.
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.
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
*/
}
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 5/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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.
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.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 6/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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
LostFocus (default for When the TextBox A TextBox that is associated with validation
TextBox.Text) control loses focus. logic (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
UpdateSource. the 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.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 8/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 9/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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">
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 10/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 11/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
<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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 12/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
<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.
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#
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 14/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
[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,
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 15/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 16/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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.
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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 17/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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.
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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 18/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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).
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 19/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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#
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 20/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
e.Accepted = true;
}
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).
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.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 21/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
XAML
The slash and property syntax can also be stacked to traverse a hierarchy of collections. The
following example binds to the current item of a collection named Offices , which is a
property of the current item of the source collection.
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.
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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 22/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
plate}"
Margin="9,0,0,0"/>
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 a singleton 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:
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 23/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 25/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
<Setter Property="BorderBrush" Value="DodgerBlue"
TargetName="border" />
<Setter Property="Foreground" Value="Navy" TargetName="descrip‐
tionTitle" />
<Setter Property="Foreground" Value="Navy" TargetName="current‐
PriceTitle" />
<Setter Property="BorderThickness" Value="3" TargetName="bor‐
der" />
<Setter Property="Padding" Value="5" TargetName="border" />
</DataTrigger.Setters>
</DataTrigger>
<DataTrigger Binding="{Binding Path=SpecialFeatures}">
<DataTrigger.Value>
<src:SpecialFeatures>Highlight</src:SpecialFeatures>
</DataTrigger.Value>
<Setter Property="BorderBrush" Value="Orange" TargetName="border"
/>
<Setter Property="Foreground" Value="Navy" TargetName="description‐
Title" />
<Setter Property="Foreground" Value="Navy" TargetName="current‐
PriceTitle" />
<Setter Property="Visibility" Value="Visible" TargetName="star" />
<Setter Property="BorderThickness" Value="3" TargetName="border" />
<Setter Property="Padding" Value="5" TargetName="border" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
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.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 26/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
property.
XAML
A ValidationRule object checks whether the value of a property is valid. WPF has two types
of built-in ValidationRule objects:
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#
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 27/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
XAML
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 28/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
XAML
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="20">!</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 29/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
</Style.Triggers>
</Style>
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.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 30/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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.
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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 31/32
1/13/24, 2:47 PM Data binding overview - WPF .NET | Microsoft Learn
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
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-8.0 32/32