Initial WPF content migrated (#17)

* Reset branch for WPF changes

* Convert BMP to PNG; fix link-out-of-scope err

* Add snippets for WPF... 6794 files!!!!

* Add missing snippets

* update file updated between migration

* Fix paths to include

* update breadcrumb and toc

* fix index links

* fix index links

* fix index links

* fix markdown
This commit is contained in:
Andy De George
2020-09-04 09:46:28 -07:00
committed by GitHub
parent dba50d6bf1
commit da363692ff
8215 changed files with 508408 additions and 11 deletions
@@ -0,0 +1,28 @@
---
title: Attribute (XElement dynamic property)
ms.date: 10/22/2019
ms.topic: reference
---
# Attribute (XElement dynamic property)
Gets an indexer used to retrieve the attribute instance that corresponds to the specified expanded name.
## Syntax
```xaml
elem.Attribute[{namespaceName}attribName]
```
## Property value/return value
An indexer of the type `XAttribute Item(String expandedName)`. This indexer takes the expanded name of the specified attribute and returns the corresponding <xref:System.Xml.Linq.XAttribute>, or `null` if there is no attribute with the specified name.
## Remarks
This property is equivalent to the <xref:System.Xml.Linq.XElement.Attribute%2A> method of the <xref:System.Xml.Linq.XElement?displayProperty=fullName> class.
## See also
- <xref:System.Xml.Linq.XElement.Attribute%2A?displayProperty=fullName>
- [XElement Class Dynamic Properties](attribute-xelement-dynamic-property.md)
- [Value](value-xattribute-dynamic-property.md)
@@ -0,0 +1,143 @@
---
title: "Binding Declarations Overview"
description: Learn how to declare a binding in XAML for your application development in Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "markup extensions [WPF]"
- "data binding [WPF], declarations"
- "object element syntax [WPF]"
- "binding data [WPF], declarations"
- "syntax [WPF], object elements"
- "binding declarations [WPF]"
ms.assetid: b97fd626-4c0d-4761-872a-2bca5820da2c
---
# Binding Declarations Overview
This topic discusses the different ways you can declare a binding.
<a name="Prereq"></a>
## Prerequisites
Before reading this topic, it is important that you are familiar with the concept and usage of markup extensions. For more information about markup extensions, see [Markup Extensions and WPF XAML](../advanced/markup-extensions-and-wpf-xaml.md).
This topic does not cover data binding concepts. For a discussion of data binding concepts, see [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview).
<a name="BindinginXAML"></a>
## Declaring a Binding in XAML
This section discusses how to declare a binding in XAML.
<a name="MarkupExtensionSyntax"></a>
### Markup Extension Usage
<xref:System.Windows.Data.Binding> is a markup extension. When you use the binding extension to declare a binding, the declaration consists of a series of clauses following the `Binding` keyword and separated by commas (,). The clauses in the binding declaration can be in any order and there are many possible combinations. The clauses are *Name*=*Value* pairs where *Name* is the name of the <xref:System.Windows.Data.Binding> property and *Value* is the value you are setting for the property.
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 <xref:System.Windows.Controls.TextBox.Text%2A?displayProperty=nameWithType> property using the binding extension, specifying the <xref:System.Windows.Data.Binding.Source%2A> and <xref:System.Windows.Data.Binding.Path%2A> properties.
[!code-xaml[SimpleBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/SimpleBinding/CSharp/Page1.xaml#L37-L37)]
You can specify most of the properties of the <xref:System.Windows.Data.Binding> class this way. For more information about the binding extension as well as for a list of <xref:System.Windows.Data.Binding> properties that cannot be set using the binding extension, see the [Binding Markup Extension](../advanced/binding-markup-extension.md) overview.
<a name="ObjectElementSyntax"></a>
### Object Element Syntax
Object element syntax is an alternative to creating the binding declaration. In most cases, there is no particular advantage to using either the markup extension or the object element syntax. However, in cases which the markup extension does not support your scenario, such as when your property value is of a non-string type for which no type conversion exists, you need to use the object element syntax.
The following is an example of both the object element syntax and the markup extension usage:
[!code-xaml[BindConversionMarkup#1](~/samples/snippets/csharp/VS_Snippets_Wpf/BindConversionMarkup/CSharp/Page1.xaml#1)]
The example binds the <xref:System.Windows.Controls.TextBlock.Foreground%2A> property by declaring a binding using the extension syntax. The binding declaration for the <xref:System.Windows.Controls.TextBlock.Text%2A> property uses the object element syntax.
For more information about the different terms, see [XAML Syntax In Detail](../advanced/xaml-syntax-in-detail.md).
<a name="MBandPB"></a>
### MultiBinding and PriorityBinding
<xref:System.Windows.Data.MultiBinding> and <xref:System.Windows.Data.PriorityBinding> do not support the XAML extension syntax. Therefore, you must use the object element syntax if you are declaring a <xref:System.Windows.Data.MultiBinding> or a <xref:System.Windows.Data.PriorityBinding> in XAML.
<a name="BindinginCode"></a>
## Creating a Binding in Code
Another way to specify a binding is to set properties directly on a <xref:System.Windows.Data.Binding> object in code. The following example shows how to create a <xref:System.Windows.Data.Binding> object and specify the properties in code. In this example, `TheConverter` is an object that implements the <xref:System.Windows.Data.IValueConverter> interface.
[!code-csharp[BindConversion#1](~/samples/snippets/csharp/VS_Snippets_Wpf/BindConversion/CSharp/Window1.xaml.cs#1)]
[!code-vb[BindConversion#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/BindConversion/visualbasic/window1.xaml.vb#1)]
If the object you are binding is a <xref:System.Windows.FrameworkElement> or a <xref:System.Windows.FrameworkContentElement> you can call the `SetBinding` method on your object directly instead of using <xref:System.Windows.Data.BindingOperations.SetBinding%2A?displayProperty=nameWithType>. For an example, see [Create a Binding in Code](how-to-create-a-binding-in-code.md).
<a name="Path_Syntax"></a>
## Binding Path Syntax
Use the <xref:System.Windows.Data.Binding.Path%2A> property to specify the source value you want to bind to:
- In the simplest case, the <xref:System.Windows.Data.Binding.Path%2A> 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 <xref:System.Windows.Controls.DockPanel.Dock%2A?displayProperty=nameWithType>, 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.
- Indexers and subproperties can be mixed in a `Path` clause; for example, `Path=ShoppingCart.ShippingInfo[MailingAddress,Street].`
- 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 <xref:System.Windows.Data.Binding.Path%2A> in XAML, you also need to escape (using XML entities) certain characters that are special to the XML language definition:
- Use `&amp;` to escape the character "&".
- Use `&gt;` to escape the end tag ">".
- 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 [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] markup extension parser:
- Backslash (\\) is the escape character itself.
- The equal sign (=) separates property name from property value.
- Comma (,) separates properties.
- The right curly brace (}) is the end of a markup extension.
<a name="Default"></a>
## 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 do not set <xref:System.Windows.Data.Binding.ConverterCulture%2A>, 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 instance, 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 the "Entire Objects Used as a Binding Source" section in the [Binding Sources Overview](binding-sources-overview.md).
- The default <xref:System.Windows.Data.Binding.Mode%2A> 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 <xref:System.Windows.Controls.TextBox.Text%2A?displayProperty=nameWithType> and <xref:System.Windows.Controls.Primitives.RangeBase.Value%2A?displayProperty=nameWithType>, default to two-way bindings, whereas most other properties default to one-way bindings.
- The default <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> value varies between <xref:System.Windows.Data.UpdateSourceTrigger.PropertyChanged> and <xref:System.Windows.Data.UpdateSourceTrigger.LostFocus> depending on the bound dependency property as well. The default value for most dependency properties is <xref:System.Windows.Data.UpdateSourceTrigger.PropertyChanged>, while the <xref:System.Windows.Controls.TextBox.Text%2A?displayProperty=nameWithType> property has a default value of <xref:System.Windows.Data.UpdateSourceTrigger.LostFocus>.
## See also
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
- [Data Binding](../advanced/optimizing-performance-data-binding.md)
- [PropertyPath XAML Syntax](../advanced/propertypath-xaml-syntax.md)
@@ -0,0 +1,97 @@
---
title: "Binding Sources Overview"
description: Discover the types of objects you can use as the binding source for your applications in Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
helpviewer_keywords:
- "binding data [WPF], binding sources"
- "data binding [WPF], binding source"
- "binding sources [WPF]"
ms.assetid: 2df2cd11-6aac-4bdf-ab7b-ea5f464cd5ca
---
# Binding Sources Overview
In data binding, the binding source object refers to the object you obtain data from. This topic discusses the types of objects you can use as the binding source.
<a name="binding_sources"></a>
## Binding Source Types
[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] data binding supports the following binding source types:
|Binding Source|Description|
|--------------------|-----------------|
|common language runtime (CLR) objects|You can bind to public properties, sub-properties, as well as indexers, of any common language runtime (CLR) object. The binding engine uses CLR reflection to get the values of the properties. Alternatively, objects that implement <xref:System.ComponentModel.ICustomTypeDescriptor> or have a registered <xref:System.ComponentModel.TypeDescriptionProvider> also work with the binding engine.<br /><br /> For more information about how to implement a class that can serve as a binding source, see [Implementing a Class for the Binding Source](#classes) later in this topic.|
|dynamic objects|You can bind to available properties and indexers of an object that implements the <xref:System.Dynamic.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 `someObjet.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 <xref:System.Data.DataTable>. The ADO.NET <xref:System.Data.DataView> implements the <xref:System.ComponentModel.IBindingList> interface, which provides change notifications that the binding engine listens for.|
|XML objects|You can bind to and run `XPath` queries on an <xref:System.Xml.XmlNode>, <xref:System.Xml.XmlDocument>, or <xref:System.Xml.XmlElement>. A convenient way to access XML data that is the binding source in markup is to use an <xref:System.Windows.Data.XmlDataProvider> object. For more information, see [Bind to XML Data Using an XMLDataProvider and XPath Queries](how-to-bind-to-xml-data-using-an-xmldataprovider-and-xpath-queries.md).<br /><br /> You can also bind to an <xref:System.Xml.Linq.XElement> or <xref:System.Xml.Linq.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 <xref:System.Windows.Data.ObjectDataProvider> object. For more information, see [Bind to XDocument, XElement, or LINQ for XML Query Results](how-to-bind-to-xdocument-xelement-or-linq-for-xml-query-results.md).|
|<xref:System.Windows.DependencyObject> objects|You can bind to dependency properties of any <xref:System.Windows.DependencyObject>. For an example, see [Bind the Properties of Two Controls](how-to-bind-the-properties-of-two-controls.md).|
<a name="classes"></a>
## Implementing a Class for the Binding Source
You can create your own binding sources. This section discusses the things you need to know if you are implementing a class to serve as a binding source.
### Providing Change Notifications
If you are using either <xref:System.Windows.Data.BindingMode.OneWay> or <xref:System.Windows.Data.BindingMode.TwoWay> binding (because you want your [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] to update when the binding source properties change dynamically), you must implement a suitable property changed notification mechanism. The recommended mechanism is for the CLR or dynamic class to implement the <xref:System.ComponentModel.INotifyPropertyChanged> interface. For more information, see [Implement Property Change Notification](how-to-implement-property-change-notification.md).
If you create a CLR object that does not implement <xref:System.ComponentModel.INotifyPropertyChanged>, then you must arrange for your own notification system to make sure that the data used in a binding stays current. You can provide change notifications by supporting the `PropertyChanged` pattern for each property that you want change notifications for. To support this pattern, you define a *PropertyName*Changed event for each property, where *PropertyName* is the name of the property. You raise the event every time the property changes.
If your binding source implements one of these notification mechanisms, target updates happen automatically. If for any reason your binding source does not provide the proper property changed notifications, you have the option to use the <xref:System.Windows.Data.BindingExpression.UpdateTarget%2A> method to update the target property explicitly.
### Other Characteristics
The following list provides other important points to note:
- If you want to create the object in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)], the class must have a parameterless constructor. In some .NET languages, such as C#, the parameterless constructor might be created for you.
- The properties you use as binding source properties for a binding must be public properties of your class. Explicitly defined interface properties cannot be accessed for binding purposes, nor can protected, private, internal, or virtual properties that have no base implementation.
- You cannot bind to public fields.
- 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 is 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 <xref:System.Windows.Data.IValueConverter>.
<a name="objects"></a>
## Using Entire Objects as a Binding Source
You can use an entire object as a binding source. You can specify a binding source by using the <xref:System.Windows.Data.Binding.Source%2A> or the <xref:System.Windows.FrameworkElement.DataContext%2A> property, and then provide a blank binding declaration: `{Binding}`. Scenarios in which this is useful include binding to objects that are of type string, binding to objects with multiple properties you are interested in, or binding to collection objects. For an example of binding to an entire collection object, see [Use the Master-Detail Pattern with Hierarchical Data](how-to-use-the-master-detail-pattern-with-hierarchical-data.md).
Note that 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 does not exist) or a <xref:System.Windows.DataTemplate>. For more information about converters, see the Data Conversion section of [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview). For more information about data templates, see [Data Templating Overview](data-templating-overview.md).
<a name="collections"></a>
## Using Collection Objects as a Binding Source
Often, the object you want to use as the binding source is a collection of custom objects. Each object serves as the source for one instance of a repeated binding. For example, you might have a `CustomerOrders` collection that consists of `CustomerOrder` objects, where your application iterates over the collection to determine how many orders exist and the data contained in each.
You can enumerate over any collection that implements the <xref:System.Collections.IEnumerable> interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] automatically, the collection must implement the <xref:System.Collections.Specialized.INotifyCollectionChanged> interface. This interface exposes an event that must be raised whenever the underlying collection changes.
The <xref:System.Collections.ObjectModel.ObservableCollection%601> class is a built-in implementation of a data collection that exposes the <xref:System.Collections.Specialized.INotifyCollectionChanged> interface. The individual data objects within the collection must satisfy the requirements described in the preceding sections. For an example, see [Create and Bind to an ObservableCollection](how-to-create-and-bind-to-an-observablecollection.md). Before implementing your own collection, consider using <xref:System.Collections.ObjectModel.ObservableCollection%601> or one of the existing collection classes, such as <xref:System.Collections.Generic.List%601>, <xref:System.Collections.ObjectModel.Collection%601>, and <xref:System.ComponentModel.BindingList%601>, among many others.
WPF never binds directly to a collection. If you specify a collection as a binding source, WPF actually binds to the collection's default view. For information about default views, see [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview).
If you have an advanced scenario and you want to implement your own collection, consider using the <xref:System.Collections.IList> interface. <xref:System.Collections.IList> provides a non-generic collection of objects that can be individually accessed by index, which can improve performance.
<a name="permissions"></a>
## Permission Requirements in Data Binding
When data binding, you must consider the trust level of the application. The following table summarizes what property types can be bound to in an application that is executing in either full trust or partial trust:
|Property type<br /><br /> (all access modifiers)|Dynamic object property|Dynamic object property|CLR property|CLR property|Dependency property|Dependency property|
|------------------------------------------------|-----------------------------|-----------------------------|------------------|------------------|-------------------------|-------------------------|
|**Trust level**|**Full trust**|**Partial trust**|**Full trust**|**Partial trust**|**Full trust**|**Partial trust**|
|Public class|Yes|Yes|Yes|Yes|Yes|Yes|
|Non-public class|Yes|No|Yes|No|Yes|Yes|
This table describes the following important points about permission requirements in data binding:
- For CLR properties, data binding works as long as the binding engine is able to access the binding source property using reflection. Otherwise, the binding engine issues a warning that the property cannot be found and uses the fallback value or the default value, if it is available.
- You can bind to properties on dynamic objects that are defined at compile time or run time.
- You can always bind to dependency properties.
The permission requirement for XML binding is similar. In a partial-trust sandbox, <xref:System.Windows.Data.XmlDataProvider> fails when it does not have permissions to access the specified data.
Objects with an anonymous type are internal. You can bind to properties of anonymous types only when running in full trust. For more information about anonymous types, see [Anonymous Types (C# Programming Guide)](/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types) or [Anonymous Types (Visual Basic)](/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/anonymous-types) (Visual Basic).
For more information about partial-trust security, see [WPF Partial Trust Security](../wpf-partial-trust-security.md).
## See also
- <xref:System.Windows.Data.ObjectDataProvider>
- <xref:System.Windows.Data.XmlDataProvider>
- [Specify the Binding Source](how-to-specify-the-binding-source.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [WPF Data Binding with LINQ to XML Overview](wpf-data-binding-with-linq-to-xml-overview.md)
- [Optimize data binding performance](../advanced/optimizing-performance-data-binding.md)
@@ -0,0 +1,39 @@
- name: Docs
tocHref: /
topicHref: /
items:
- name: .NET
tocHref: /dotnet/
topicHref: /dotnet/index
items:
- name: .NET Framework
tocHref: /dotnet/framework/
topicHref: /dotnet/framework/index
items:
- name: Windows Presentation Foundation
tocHref: /dotnet/framework/wpf/
topicHref: /dotnet/framework/wpf/index
items:
- name: Data
tocHref: /dotnet/framework/wpf/data/
topicHref: /dotnet/framework/wpf/data/index
- name: Docs
tocHref: /
topicHref: /
items:
- name: .NET
tocHref: /dotnet/
topicHref: /dotnet/index
items:
- name: .NET Framework
tocHref: /dotnet/framework/
topicHref: /dotnet/framework/index
items:
- name: Windows Presentation Foundation
tocHref: /dotnet/desktop-wpf/
topicHref: /dotnet/framework/wpf/index
items:
- name: Data
tocHref: /dotnet/desktop-wpf/data/
topicHref: /dotnet/framework/wpf/data/index
@@ -0,0 +1,62 @@
---
title: How-to articles for data binding
ms.date: "03/30/2017"
f1_keywords:
- "AutoGeneratedOrientationPage"
helpviewer_keywords:
- "data binding [WPF], how-to topics"
- "binding data [WPF], how-to topics"
ms.assetid: a3b2563e-d879-41a7-9dfd-ac56b27fdcad
---
# Data binding how-to topics
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](how-to-create-a-simple-binding.md)
- [Specify the Binding Source](how-to-specify-the-binding-source.md)
- [Make Data Available for Binding in XAML](how-to-make-data-available-for-binding-in-xaml.md)
- [Control When the TextBox Text Updates the Source](how-to-control-when-the-textbox-text-updates-the-source.md)
- [Specify the Direction of the Binding](how-to-specify-the-direction-of-the-binding.md)
- [Bind to a Collection and Display Information Based on Selection](how-to-bind-to-a-collection-and-display-information-based-on-selection.md)
- [Bind to an Enumeration](how-to-bind-to-an-enumeration.md)
- [Bind the Properties of Two Controls](how-to-bind-the-properties-of-two-controls.md)
- [Implement Binding Validation](how-to-implement-binding-validation.md)
- [Implement Validation Logic on Custom Objects](how-to-implement-validation-logic-on-custom-objects.md)
- [Get the Binding Object from a Bound Target Property](how-to-get-the-binding-object-from-a-bound-target-property.md)
- [Implement a CompositeCollection](how-to-implement-a-compositecollection.md)
- [Convert Bound Data](how-to-convert-bound-data.md)
- [Create a Binding in Code](how-to-create-a-binding-in-code.md)
- [Get the Default View of a Data Collection](how-to-get-the-default-view-of-a-data-collection.md)
- [Navigate Through the Objects in a Data CollectionView](how-to-navigate-through-the-objects-in-a-data-collectionview.md)
- [Filter Data in a View](how-to-filter-data-in-a-view.md)
- [Sort Data in a View](how-to-sort-data-in-a-view.md)
- [Sort and Group Data Using a View in XAML](how-to-sort-and-group-data-using-a-view-in-xaml.md)
- [Use the Master-Detail Pattern with Hierarchical Data](how-to-use-the-master-detail-pattern-with-hierarchical-data.md)
- [Use the Master-Detail Pattern with Hierarchical XML Data](how-to-use-the-master-detail-pattern-with-hierarchical-xml-data.md)
- [Produce a Value Based on a List of Bound Items](how-to-produce-a-value-based-on-a-list-of-bound-items.md)
- [Implement Property Change Notification](how-to-implement-property-change-notification.md)
- [Create and Bind to an ObservableCollection](how-to-create-and-bind-to-an-observablecollection.md)
- [Implement PriorityBinding](how-to-implement-prioritybinding.md)
- [Bind to XML Data Using an XMLDataProvider and XPath Queries](how-to-bind-to-xml-data-using-an-xmldataprovider-and-xpath-queries.md)
- [Bind to XDocument, XElement, or LINQ for XML Query Results](how-to-bind-to-xdocument-xelement-or-linq-for-xml-query-results.md)
- [Bind to the Results of a LINQ Query](how-to-bind-to-the-results-of-a-linq-query.md)
- [Use XML Namespaces in Data Binding](how-to-use-xml-namespaces-in-data-binding.md)
- [Bind to an ADO.NET Data Source](how-to-bind-to-an-ado-net-data-source.md)
- [Bind to a Method](how-to-bind-to-a-method.md)
- [Set Up Notification of Binding Updates](how-to-set-up-notification-of-binding-updates.md)
- [Clear Bindings](how-to-clear-bindings.md)
- [Find DataTemplate-Generated Elements](how-to-find-datatemplate-generated-elements.md)
## Reference
- <xref:System.Windows.Data>
- <xref:System.Windows.Data.Binding>
- <xref:System.Windows.DataTemplate>
- <xref:System.Windows.Controls.DataTemplateSelector>
## Related sections
- [Data binding in WPF](/dotnet/desktop-wpf/data/data-binding-overview)
- [Data binding performance](../advanced/optimizing-performance-data-binding.md)
@@ -0,0 +1,197 @@
---
title: "Data Templating Overview"
description: Explore the data templating model flexibility that define the presentation of your data in Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data binding [WPF], templates"
- "binding data [WPF], templates"
- "templates [WPF], data"
- "data templates [WPF]"
ms.assetid: 0f4d9f8c-0230-4013-bd7b-e8e7fed01b4a
---
# Data Templating Overview
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 <xref:System.Windows.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.
<a name="Prerequisites"></a>
## 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](/dotnet/desktop-wpf/data/data-binding-overview).
<xref:System.Windows.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 <xref:System.Windows.Style> to set properties on controls, see the [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview) topic.
In addition, it is important to understand `Resources`, which are essentially what enable objects such as <xref:System.Windows.Style> and <xref:System.Windows.DataTemplate> to be reusable. For more information on resources, see [XAML Resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define).
<a name="DataTemplating_Basic"></a>
## Data Templating Basics
To demonstrate why <xref:System.Windows.DataTemplate> is important, let's walk through a data binding example. In this example, we have a <xref:System.Windows.Controls.ListBox> that is bound to a list of `Task` objects. Each `Task` object has a `TaskName` (string), a `Description` (string), a `Priority` (int), and a property of type `TaskType`, which is an `Enum` with values `Home` and `Work`.
[!code-xaml[DataTemplatingIntro_snip#Resources](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#resources)]
[!code-xaml[DataTemplatingIntro_snip#UI1](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#ui1)]
[!code-xaml[DataTemplatingIntro_snip#UI2](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#ui2)]
<a name="without_a_datatemplate"></a>
### Without a DataTemplate
Without a <xref:System.Windows.DataTemplate>, our <xref:System.Windows.Controls.ListBox> currently looks like this:
![Data templating sample screenshot](./media/datatemplatingintro-fig1.png "DataTemplatingIntro_fig1")
What's happening is that without any specific instructions, the <xref:System.Windows.Controls.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 <xref:System.Windows.Controls.ListBox> displays the string representation of each source object in the underlying collection.
For example, if the `Task` class overrides the `ToString` method this way, where `name` is the field for the `TaskName` property:
[!code-csharp[DataTemplatingIntro_snip#ToString](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Data.cs#tostring)]
[!code-vb[DataTemplatingIntro_snip#ToString](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DataTemplatingIntro_snip/visualbasic/data.vb#tostring)]
Then the <xref:System.Windows.Controls.ListBox> looks like the following:
![Data templating sample screenshot](./media/datatemplatingintro-fig2.png "DataTemplatingIntro_fig2")
However, that is limiting and inflexible. Also, if you are binding to XML data, you wouldn't be able to override `ToString`.
<a name="defining_simple_datatemplate"></a>
### Defining a Simple DataTemplate
The solution is to define a <xref:System.Windows.DataTemplate>. One way to do that is to set the <xref:System.Windows.Controls.ItemsControl.ItemTemplate%2A> property of the <xref:System.Windows.Controls.ListBox> to a <xref:System.Windows.DataTemplate>. What you specify in your <xref:System.Windows.DataTemplate> becomes the visual structure of your data object. The following <xref:System.Windows.DataTemplate> is fairly simple. We are giving instructions that each item appears as three <xref:System.Windows.Controls.TextBlock> elements within a <xref:System.Windows.Controls.StackPanel>. Each <xref:System.Windows.Controls.TextBlock> element is bound to a property of the `Task` class.
[!code-xaml[DataTemplatingIntro_snip#Inline](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#inline)]
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 <xref:System.Windows.Data.Binding.XPath%2A> to `@TaskName` (if `TaskName` is an attribute of your XML node).
Now our <xref:System.Windows.Controls.ListBox> looks like the following:
![Data templating sample screenshot](./media/datatemplatingintro-fig3.png "DataTemplatingIntro_fig3")
<a name="defining_datatemplate_as_a_resource"></a>
### Creating the DataTemplate as a Resource
In the above example, we defined the <xref:System.Windows.DataTemplate> inline. It is more common to define it in the resources section so it can be a reusable object, as in the following example:
[!code-xaml[DataTemplatingIntro_snip#R1](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#r1)]
[!code-xaml[DataTemplatingIntro_snip#AsResource](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#asresource)]
[!code-xaml[DataTemplatingIntro_snip#R2](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#r2)]
Now you can use `myTaskTemplate` as a resource, as in the following example:
[!code-xaml[DataTemplatingIntro_snip#MyTaskTemplate](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#mytasktemplate)]
Because `myTaskTemplate` is a resource, you can now use it on other controls that have a property that takes a <xref:System.Windows.DataTemplate> type. As shown above, for <xref:System.Windows.Controls.ItemsControl> objects, such as the <xref:System.Windows.Controls.ListBox>, it is the <xref:System.Windows.Controls.ItemsControl.ItemTemplate%2A> property. For <xref:System.Windows.Controls.ContentControl> objects, it is the <xref:System.Windows.Controls.ContentControl.ContentTemplate%2A> property.
<a name="Styling_DataType"></a>
### The DataType Property
The <xref:System.Windows.DataTemplate> class has a <xref:System.Windows.DataTemplate.DataType%2A> property that is very similar to the <xref:System.Windows.Style.TargetType%2A> property of the <xref:System.Windows.Style> class. Therefore, instead of specifying an `x:Key` for the <xref:System.Windows.DataTemplate> in the above example, you can do the following:
[!code-xaml[DataTemplatingIntro_snip#DataType](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#datatype)]
This <xref:System.Windows.DataTemplate> gets applied automatically to all `Task` objects. Note that in this case the `x:Key` is set implicitly. Therefore, if you assign this <xref:System.Windows.DataTemplate> an `x:Key` value, you are overriding the implicit `x:Key` and the <xref:System.Windows.DataTemplate> would not be applied automatically.
If you are binding a <xref:System.Windows.Controls.ContentControl> to a collection of `Task` objects, the <xref:System.Windows.Controls.ContentControl> does not use the above <xref:System.Windows.DataTemplate> automatically. This is because the binding on a <xref:System.Windows.Controls.ContentControl> needs more information to distinguish whether you want to bind to an entire collection or the individual objects. If your <xref:System.Windows.Controls.ContentControl> is tracking the selection of an <xref:System.Windows.Controls.ItemsControl> type, you can set the <xref:System.Windows.Data.Binding.Path%2A> property of the <xref:System.Windows.Controls.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](how-to-bind-to-a-collection-and-display-information-based-on-selection.md). Otherwise, you need to specify the <xref:System.Windows.DataTemplate> explicitly by setting the <xref:System.Windows.Controls.ContentControl.ContentTemplate%2A> property.
The <xref:System.Windows.DataTemplate.DataType%2A> property is particularly useful when you have a <xref:System.Windows.Data.CompositeCollection> of different types of data objects. For an example, see [Implement a CompositeCollection](how-to-implement-a-compositecollection.md).
<a name="adding_more_to_datatemplate"></a>
## Adding More to the DataTemplate
Currently the data appears with the necessary information, but there's definitely room for improvement. Let's improve on the presentation by adding a <xref:System.Windows.Controls.Border>, a <xref:System.Windows.Controls.Grid>, and some <xref:System.Windows.Controls.TextBlock> elements that describe the data that is being displayed.
[!code-xaml[DataTemplatingIntro#AddingMore](~/samples/snippets/xaml/VS_Snippets_Wpf/DataTemplatingIntro/xaml/window1.xaml#addingmore)]
[!code-xaml[DataTemplatingIntro#AddingMore2](~/samples/snippets/xaml/VS_Snippets_Wpf/DataTemplatingIntro/xaml/window1.xaml#addingmore2)]
The following screenshot shows the <xref:System.Windows.Controls.ListBox> with this modified <xref:System.Windows.DataTemplate>:
![Data templating sample screenshot](./media/datatemplatingintro-fig4.png "DataTemplatingIntro_fig4")
We can set <xref:System.Windows.Controls.Control.HorizontalContentAlignment%2A> to <xref:System.Windows.HorizontalAlignment.Stretch> on the <xref:System.Windows.Controls.ListBox> to make sure the width of the items takes up the entire space:
[!code-xaml[DataTemplatingIntro_snip#Stretch](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#stretch)]
With the <xref:System.Windows.Controls.Control.HorizontalContentAlignment%2A> property set to <xref:System.Windows.HorizontalAlignment.Stretch>, the <xref:System.Windows.Controls.ListBox> now looks like this:
![Data templating sample screenshot](./media/datatemplatingintro-fig5.png "DataTemplatingIntro_fig5")
<a name="DataTrigger_to_Apply_Property_Values"></a>
### Use DataTriggers to Apply Property Values
The current presentation does not tell us whether a `Task` is a home task or an office task. Remember that the `Task` object has a `TaskType` property of type `TaskType`, which is an enumeration with values `Home` and `Work`.
In the following example, the <xref:System.Windows.DataTrigger> sets the <xref:System.Windows.Controls.Border.BorderBrush%2A> of the element named `border` to `Yellow` if the `TaskType` property is `TaskType.Home`.
[!code-xaml[DataTemplatingIntro#DT](~/samples/snippets/xaml/VS_Snippets_Wpf/DataTemplatingIntro/xaml/window1.xaml#dt)]
[!code-xaml[DataTemplatingIntro#DataTrigger](~/samples/snippets/xaml/VS_Snippets_Wpf/DataTemplatingIntro/xaml/window1.xaml#datatrigger)]
[!code-xaml[DataTemplatingIntro#AddingMore2](~/samples/snippets/xaml/VS_Snippets_Wpf/DataTemplatingIntro/xaml/window1.xaml#addingmore2)]
Our application now looks like the following. Home tasks appear with a yellow border and office tasks appear with an aqua border:
![Data templating sample screenshot](./media/datatemplatingintro-fig6.png "DataTemplatingIntro_fig6")
In this example the <xref:System.Windows.DataTrigger> uses a <xref:System.Windows.Setter> to set a property value. The trigger classes also have the <xref:System.Windows.TriggerBase.EnterActions%2A> and <xref:System.Windows.TriggerBase.ExitActions%2A> properties that allow you to start a set of actions such as animations. In addition, there is also a <xref:System.Windows.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 <xref:System.Windows.Controls.Border.BorderBrush%2A> 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 <xref:System.Windows.Data.IValueConverter>.
<a name="what_belongs_in_datatemplate"></a>
### What Belongs in a DataTemplate?
In the previous example, we placed the trigger within the <xref:System.Windows.DataTemplate> using the <xref:System.Windows.DataTemplate.Triggers%2A?displayProperty=nameWithType> property. The <xref:System.Windows.Setter> of the trigger sets the value of a property of an element (the <xref:System.Windows.Controls.Border> element) that is within the <xref:System.Windows.DataTemplate>. However, if the properties that your `Setters` are concerned with are not properties of elements that are within the current <xref:System.Windows.DataTemplate>, it may be more suitable to set the properties using a <xref:System.Windows.Style> that is for the <xref:System.Windows.Controls.ListBoxItem> class (if the control you are binding is a <xref:System.Windows.Controls.ListBox>). For example, if you want your <xref:System.Windows.Trigger> to animate the <xref:System.Windows.UIElement.Opacity%2A> value of the item when a mouse points to an item, you define triggers within a <xref:System.Windows.Controls.ListBoxItem> style. For an example, see the [Introduction to Styling and Templating Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Styles%20&%20Templates/IntroToStylingAndTemplating).
In general, keep in mind that the <xref:System.Windows.DataTemplate> is being applied to each of the generated <xref:System.Windows.Controls.ListBoxItem> (for more information about how and where it is actually applied, see the <xref:System.Windows.Controls.ItemsControl.ItemTemplate%2A> page.). Your <xref:System.Windows.DataTemplate> is concerned with only the presentation and appearance of the data objects. In most cases, all other aspects of presentation, such as what an item looks like when it is selected or how the <xref:System.Windows.Controls.ListBox> lays out the items, do not belong in the definition of a <xref:System.Windows.DataTemplate>. For an example, see the [Styling and Templating an ItemsControl](#DataTemplating_ItemsControl) section.
<a name="Styling_StyleSelection"></a>
## Choosing a DataTemplate Based on Properties of the Data Object
In [The DataType Property](#Styling_DataType) section, we discussed that you can define different data templates for different data objects. That is especially useful when you have a <xref:System.Windows.Data.CompositeCollection> of different types or collections with items of different types. In the [Use DataTriggers to Apply Property Values](#DataTrigger_to_Apply_Property_Values) section, we have shown that if you have a collection of the same type of data objects you can create a <xref:System.Windows.DataTemplate> and then use triggers to apply changes based on the property values of each data object. However, triggers allow you to apply property values or start animations but they don't give you the flexibility to reconstruct the structure of your data objects. Some scenarios may require you to create a different <xref:System.Windows.DataTemplate> for data objects that are of the same type but have different properties.
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 <xref:System.Windows.DataTemplate> for the display of the high-priority `Task` objects. Let's add the following <xref:System.Windows.DataTemplate> to the resources section:
[!code-xaml[DataTemplatingIntro_snip#ImportantTemplate](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#importanttemplate)]
This example uses the [DataTemplate.Resources](xref:System.Windows.FrameworkTemplate.Resources%2A) property. Resources defined in that section are shared by the elements within the <xref:System.Windows.DataTemplate>.
To supply logic to choose which <xref:System.Windows.DataTemplate> to use based on the `Priority` value of the data object, create a subclass of <xref:System.Windows.Controls.DataTemplateSelector> and override the <xref:System.Windows.Controls.DataTemplateSelector.SelectTemplate%2A> method. In the following example, the <xref:System.Windows.Controls.DataTemplateSelector.SelectTemplate%2A> 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 <xref:System.Windows.Window> element.
[!code-csharp[DataTemplatingIntro_snip#DTSClass](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/TaskListDataTemplateSelector.cs#dtsclass)]
[!code-vb[DataTemplatingIntro_snip#DTSClass](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DataTemplatingIntro_snip/visualbasic/tasklistdatatemplateselector.vb#dtsclass)]
We can then declare the `TaskListDataTemplateSelector` as a resource:
[!code-xaml[DataTemplatingIntro_snip#R1](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#r1)]
[!code-xaml[DataTemplatingIntro_snip#DTS](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#dts)]
[!code-xaml[DataTemplatingIntro_snip#R2](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#r2)]
To use the template selector resource, assign it to the <xref:System.Windows.Controls.ItemsControl.ItemTemplateSelector%2A> property of the <xref:System.Windows.Controls.ListBox>. The <xref:System.Windows.Controls.ListBox> calls the <xref:System.Windows.Controls.DataTemplateSelector.SelectTemplate%2A> method of the `TaskListDataTemplateSelector` for each of the items in the underlying collection. The call passes the data object as the item parameter. The <xref:System.Windows.DataTemplate> that is returned by the method is then applied to that data object.
[!code-xaml[DataTemplatingIntro_snip#ItemTemplateSelector](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#itemtemplateselector)]
With the template selector in place, the <xref:System.Windows.Controls.ListBox> now appears as follows:
![Data templating sample screenshot](./media/datatemplatingintro-fig7.png "DataTemplatingIntro_fig7")
This concludes our discussion of this example. For the complete sample, see [Introduction to Data Templating Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Data%20Binding/DataTemplatingIntro).
<a name="DataTemplating_ItemsControl"></a>
## Styling and Templating an ItemsControl
Even though the <xref:System.Windows.Controls.ItemsControl> is not the only control type that you can use a <xref:System.Windows.DataTemplate> with, it is a very common scenario to bind an <xref:System.Windows.Controls.ItemsControl> to a collection. In the [What Belongs in a DataTemplate](#what_belongs_in_datatemplate) section we discussed that the definition of your <xref:System.Windows.DataTemplate> should only be concerned with the presentation of data. In order to know when it is not suitable to use a <xref:System.Windows.DataTemplate> it is important to understand the different style and template properties provided by the <xref:System.Windows.Controls.ItemsControl>. The following example is designed to illustrate the function of each of these properties. The <xref:System.Windows.Controls.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.
[!code-xaml[DataTemplatingIntro_snip#ItemsControlProperties](~/samples/snippets/csharp/VS_Snippets_Wpf/DataTemplatingIntro_snip/CSharp/Window1.xaml#itemscontrolproperties)]
The following is a screenshot of the example when it is rendered:
![ItemsControl example screenshot](./media/databinding-itemscontrolproperties.png "DataBinding_ItemsControlProperties")
Note that instead of using the <xref:System.Windows.Controls.ItemsControl.ItemTemplate%2A>, you can use the <xref:System.Windows.Controls.ItemsControl.ItemTemplateSelector%2A>. Refer to the previous section for an example. Similarly, instead of using the <xref:System.Windows.Controls.ItemsControl.ItemContainerStyle%2A>, you have the option to use the <xref:System.Windows.Controls.ItemsControl.ItemContainerStyleSelector%2A>.
Two other style-related properties of the <xref:System.Windows.Controls.ItemsControl> that are not shown here are <xref:System.Windows.Controls.ItemsControl.GroupStyle%2A> and <xref:System.Windows.Controls.ItemsControl.GroupStyleSelector%2A>.
<a name="DataTemplating_HeirarchicalDataTemplate"></a>
## Support for Hierarchical Data
So far we have only looked at how to bind to and display a single collection. Sometimes you have a collection that contains other collections. The <xref:System.Windows.HierarchicalDataTemplate> class is designed to be used with <xref:System.Windows.Controls.HeaderedItemsControl> types to display such data. In the following example, `ListLeagueList` is a list of `League` objects. Each `League` object has a `Name` and a collection of `Division` objects. Each `Division` has a `Name` and a collection of `Team` objects, and each `Team` object has a `Name`.
[!code-xaml[HierarchicalDataTemplateSnippet#HDT](~/samples/snippets/csharp/VS_Snippets_Wpf/HierarchicalDataTemplateSnippet/CS/window1.xaml#hdt)]
The example shows that with the use of <xref:System.Windows.HierarchicalDataTemplate>, you can easily display list data that contains other lists. The following is a screenshot of the example.
![HierarchicalDataTemplate sample screenshot](./media/databinding-hierarchicaldatatemplate.png "DataBinding_HierarchicalDataTemplate")
## See also
- [Data Binding](../advanced/optimizing-performance-data-binding.md)
- [Find DataTemplate-Generated Elements](how-to-find-datatemplate-generated-elements.md)
- [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [GridView Column Header Styles and Templates Overview](../controls/gridview-column-header-styles-and-templates-overview.md)
@@ -0,0 +1,31 @@
---
title: Descendants (XElement dynamic property)
ms.date: 10/22/2019
ms.topic: reference
---
# Descendants (XElement dynamic property)
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]
```
## Property value/return value
An indexer of the type `IEnumerable<XElement> Item(String expandedName)`. This indexer takes the expanded name of the specified descendant elements and returns the matching child elements in an <xref:System.Collections.IEnumerable>`<`<xref:System.Xml.Linq.XElement>`>` collection.
## Remarks
This property is equivalent to the <xref:System.Xml.Linq.XContainer.Descendants(System.Xml.Linq.XName)?displayProperty=fullName> method of the <xref:System.Xml.Linq.XContainer> class.
The elements in the returned collection are in XML source document order.
This property uses deferred execution.
## See also
- [XElement class dynamic properties](attribute-xelement-dynamic-property.md)
- [Elements](elements-xelement-dynamic-property.md)
@@ -0,0 +1,31 @@
---
title: Element (XElement dynamic property)
ms.date: 10/22/2019
ms.topic: reference
apiname:
- "XElement.Element"
apitype: "Assembly"
---
# Element (XElement dynamic property)
Gets an indexer used to retrieve the child element instance that corresponds to the specified expanded name.
## Syntax
```xaml
elem.Element[{namespaceName}localName]
```
## Property value/return value
An indexer of the type `XElement Item(String expandedName)`. This indexer takes an expanded name parameter and returns the corresponding <xref:System.Xml.Linq.XElement>, or `null` if there is no element with the specified name.
## Remarks
This property is equivalent to <xref:System.Xml.Linq.XContainer.Element%2A> method of the <xref:System.Xml.Linq.XContainer?displayProperty=fullName> class.
## See also
- <xref:System.Xml.Linq.XContainer.Element%2A?displayProperty=fullName>
- [XElement class dynamic properties](attribute-xelement-dynamic-property.md)
- [Elements](elements-xelement-dynamic-property.md)
@@ -0,0 +1,35 @@
---
title: Elements (XElement dynamic property)
ms.date: 10/22/2019
ms.topic: reference
apiname:
- "XElement.Elements"
apitype: "Assembly"
---
# Elements (XElement dynamic property)
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]
```
## Property value/return value
An indexer of the type `IEnumerable<XElement> Item(String expandedName)`. This indexer takes the expanded name of the desired child elements and returns the matching child elements in an <xref:System.Collections.IEnumerable>`<`<xref:System.Xml.Linq.XElement>`>` collection.
## Remarks
This property is equivalent to the <xref:System.Xml.Linq.XContainer.Elements(System.Xml.Linq.XName)?displayProperty=fullName> method of the <xref:System.Xml.Linq.XContainer> class.
The elements in the returned collection are in XML source document order.
This property uses deferred execution.
## See also
- [XElement class dynamic properties](attribute-xelement-dynamic-property.md)
- [Element](element-xelement-dynamic-property.md)
- [Descendants](descendants-xelement-dynamic-property.md)
@@ -0,0 +1,30 @@
---
title: "How to: Bind the Properties of Two Controls"
ms.date: "03/30/2017"
helpviewer_keywords:
- "data binding [WPF], binding properties of two controls"
- "binding properties of two controls [WPF]"
- "controls [WPF], binding properties of"
ms.assetid: 06318fac-6afd-4c7d-a277-6d7ef50f47bc
---
# How to: Bind the Properties of Two Controls
This example shows how to bind the property of one instantiated control to that of another using the <xref:System.Windows.Data.Binding.ElementName%2A> property.
## Example
The following example shows how to bind the <xref:System.Windows.Controls.Panel.Background%2A> property of a <xref:System.Windows.Controls.Canvas> to the [SelectedItem.Content](xref:System.Windows.Controls.ContentControl.Content%2A) property of a <xref:System.Windows.Controls.ComboBox>:
[!code-xaml[BindDptoDp#1](~/samples/snippets/csharp/VS_Snippets_Wpf/BindDPtoDP/CS/Window1.xaml#1)]
When this example is rendered it looks like the following:
![Screenshot showing a combo box with the value green selected and a green square.](./media/how-to-bind-the-properties-of-two-controls/data-binding-bind-background-canvas.png)
> [!NOTE]
> The binding target property (in this example, the <xref:System.Windows.Controls.Panel.Background%2A> property) must be a dependency property. For more information, see [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview).
## See also
- [Specify the Binding Source](how-to-specify-the-binding-source.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,49 @@
---
title: "How to: Bind to a Collection and Display Information Based on Selection"
description: Follow this example to find out how to bind to a collection and display information based on selection in the Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data collections [WPF], selecting data for views"
- "data binding [WPF], creating views of data collections"
- "data binding [WPF], selecting data for views"
- "data binding [WPF], binding to collections"
ms.assetid: 952a7d76-dd29-49e5-86f5-32c4530e70eb
---
# How to: Bind to a Collection and Display Information Based on Selection
In a simple master-detail scenario, you have a data-bound <xref:System.Windows.Controls.ItemsControl> such as a <xref:System.Windows.Controls.ListBox>. Based on user selection, you display more information about the selected item. This example shows how to implement this scenario.
## Example
In this example, `People` is an <xref:System.Collections.ObjectModel.ObservableCollection%601> of `Person` classes. This `Person` class contains three properties: `FirstName`, `LastName`, and `HomeTown`, all of type `string`.
[!code-xaml[CollectionBinding#Source](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionBinding/CSharp/Window1.xaml#source)]
[!code-xaml[CollectionBinding#UI](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionBinding/CSharp/Window1.xaml#ui)]
The <xref:System.Windows.Controls.ContentControl> uses the following <xref:System.Windows.DataTemplate> that defines how the information of a `Person` is presented:
[!code-xaml[CollectionBinding#DetailTemplate](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionBinding/CSharp/Window1.xaml#detailtemplate)]
The following is a screenshot of what the example produces. The <xref:System.Windows.Controls.ContentControl> shows the other properties of the person selected.
![Binding to a collection](./media/databinding-collectionbindingsample.png "DataBinding_CollectionBindingSample")
The two things to notice in this example are:
1. The <xref:System.Windows.Controls.ListBox> and the <xref:System.Windows.Controls.ContentControl> bind to the same source. The <xref:System.Windows.Data.Binding.Path%2A> properties of both bindings are not specified because both controls are binding to the entire collection object.
2. You must set the <xref:System.Windows.Controls.Primitives.Selector.IsSynchronizedWithCurrentItem%2A> property to `true` for this to work. Setting this property ensures that the selected item is always set as the <xref:System.Windows.Controls.ItemCollection.CurrentItem%2A>. Alternatively, if the <xref:System.Windows.Controls.ListBox> gets it data from a <xref:System.Windows.Data.CollectionViewSource>, it synchronizes selection and currency automatically.
Note that the `Person` class overrides the `ToString` method the following way. By default, the <xref:System.Windows.Controls.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 <xref:System.Windows.Controls.ListBox>.
[!code-csharp[CollectionBinding#ToString](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionBinding/CSharp/Data.cs#tostring)]
[!code-vb[CollectionBinding#ToString](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CollectionBinding/VisualBasic/Person.vb#tostring)]
## See also
- [Use the Master-Detail Pattern with Hierarchical Data](how-to-use-the-master-detail-pattern-with-hierarchical-data.md)
- [Use the Master-Detail Pattern with Hierarchical XML Data](how-to-use-the-master-detail-pattern-with-hierarchical-xml-data.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [Data Templating Overview](data-templating-overview.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,32 @@
---
title: "How to: Bind to a Method"
description: Follow this example to find out how to bind to the method of an object in the Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
helpviewer_keywords:
- "data binding [WPF], binding to methods using ObjectDataProvider"
- "binding [WPF], to methods"
- "methods [WPF], binding to"
ms.assetid: 5f55e71e-2182-42a0-88d1-700cc1427a7a
---
# How to: Bind to a Method
The following example shows how to bind to a method using <xref:System.Windows.Data.ObjectDataProvider>.
## 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 <xref:System.Windows.Data.ObjectDataProvider> is used to instantiate the `TemperatureScale` object. The `ConvertTemp` method is called with two specified parameters.
[!code-xaml[BindToMethod#WindowResources](~/samples/snippets/csharp/VS_Snippets_Wpf/BindToMethod/CS/Window1.xaml#windowresources)]
Now that the method is available as a resource, you can bind to its results. In the following example, the <xref:System.Windows.Controls.TextBox.Text%2A> property of the <xref:System.Windows.Controls.TextBox> and the <xref:System.Windows.Controls.Primitives.Selector.SelectedValue%2A> of the <xref:System.Windows.Controls.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 <xref:System.Windows.Data.Binding.BindsDirectlyToSource%2A> is set to `true` because we are binding to the <xref:System.Windows.Data.ObjectDataProvider.MethodParameters%2A> property of the <xref:System.Windows.Data.ObjectDataProvider> instance and not properties of the object wrapped by the <xref:System.Windows.Data.ObjectDataProvider> (the `TemperatureScale` object).
The <xref:System.Windows.Controls.ContentControl.Content%2A> of the last <xref:System.Windows.Controls.Label> updates when the user modifies the content of the <xref:System.Windows.Controls.TextBox> or the selection of the <xref:System.Windows.Controls.ComboBox>.
[!code-xaml[BindToMethod#UI](~/samples/snippets/csharp/VS_Snippets_Wpf/BindToMethod/CS/Window1.xaml#ui)]
The converter `DoubleToString` takes a double and turns it into a string in the <xref:System.Windows.Data.IValueConverter.Convert%2A> direction (from the binding source to binding target, which is the <xref:System.Windows.Controls.TextBox.Text%2A> property) and converts a `string` to a `double` in the <xref:System.Windows.Data.IValueConverter.ConvertBack%2A> direction.
The `InvalidationCharacterRule` is a <xref:System.Windows.Controls.ValidationRule> that checks for invalid characters. The default error template, which is a red border around the <xref:System.Windows.Controls.TextBox>, appears to notify users when the input value is not a double value.
## See also
- [How-to Topics](data-binding-how-to-topics.md)
- [Bind to an Enumeration](how-to-bind-to-an-enumeration.md)
@@ -0,0 +1,39 @@
---
title: "How to: Bind to an ADO.NET Data Source"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data binding [WPF], binding to ADO.NET data sources"
- "ADO.NET data sources [WPF], binding to"
- "binding [WPF], to ADO.NET data sources"
ms.assetid: a70c6d7b-7b38-4fdf-b655-4804db7c8315
---
# How to: Bind to an ADO.NET Data Source
This example shows how to bind a [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] <xref:System.Windows.Controls.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 the <xref:System.Windows.FrameworkElement.DataContext%2A> property of the <xref:System.Windows.Controls.ListBox> to the `DataSet` object.
[!code-csharp[ADODataSet#1](~/samples/snippets/csharp/VS_Snippets_Wpf/ADODataSet/CSharp/Window1.xaml.cs#1)]
[!code-vb[ADODataSet#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/ADODataSet/VisualBasic/Window1.xaml.vb#1)]
We can then bind the <xref:System.Windows.Controls.ItemsControl.ItemsSource%2A> property of the <xref:System.Windows.Controls.ListBox> to `BookTable` of the `DataSet`:
[!code-xaml[ADODataSet#2](~/samples/snippets/csharp/VS_Snippets_Wpf/ADODataSet/CSharp/Window1.xaml#2)]
`BookItemTemplate` is the <xref:System.Windows.DataTemplate> that defines how the data appears:
[!code-xaml[ADODataSet#3](~/samples/snippets/csharp/VS_Snippets_Wpf/ADODataSet/CSharp/Window1.xaml#3)]
The `IntColorConverter` converts an `int` to a color. With the use of this converter, the <xref:System.Windows.Controls.TextBlock.Background%2A> color of the third <xref:System.Windows.Controls.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
- <xref:System.Windows.Data.BindingListCollectionView>
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,22 @@
---
title: "How to: Bind to an Enumeration"
ms.date: "03/30/2017"
helpviewer_keywords:
- "binding data [WPF], enumeration"
- "data binding [WPF], enumeration"
- "enumeration [WPF]"
ms.assetid: b9091eba-1119-424e-868b-d1a4168b3732
---
# How to: Bind to an Enumeration
This example shows how to bind to an enumeration by binding to the enumeration's GetValues method.
## Example
In the following example, the <xref:System.Windows.Controls.ListBox> displays the list of <xref:System.Windows.HorizontalAlignment> enumeration values through data binding. The <xref:System.Windows.Controls.ListBox> and the <xref:System.Windows.Controls.Button> are bound such that you can change the <xref:System.Windows.FrameworkElement.HorizontalAlignment%2A> property value of the <xref:System.Windows.Controls.Button> by selecting a value in the <xref:System.Windows.Controls.ListBox>.
[!code-xaml[BindToEnum#BindToEnum](~/samples/snippets/csharp/VS_Snippets_Wpf/BindToEnum/CS/Window1.xaml#bindtoenum)]
## See also
- [Bind to a Method](how-to-bind-to-a-method.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,32 @@
---
title: "How to: Bind to the Results of a LINQ Query"
ms.date: "03/30/2017"
helpviewer_keywords:
- "running a LINQ query [WPF], bind to results"
- "binding to LINQ query results [WPF]"
ms.assetid: ff2844d9-17ed-4ea6-aab1-5111af0bc684
---
# How to: Bind to the Results of a LINQ Query
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.
[!code-xaml[LinqExample#UI](~/samples/snippets/csharp/VS_Snippets_Wpf/LinqExample/CSharp/Window1.xaml#ui)]
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 <xref:System.Windows.FrameworkElement.DataContext%2A>:
[!code-csharp[LinqExample#Using](~/samples/snippets/csharp/VS_Snippets_Wpf/LinqExample/CSharp/Window1.xaml.cs#using)]
[!code-csharp[LinqExample#Tasks](~/samples/snippets/csharp/VS_Snippets_Wpf/LinqExample/CSharp/Window1.xaml.cs#tasks)]
[!code-csharp[LinqExample#Handler](~/samples/snippets/csharp/VS_Snippets_Wpf/LinqExample/CSharp/Window1.xaml.cs#handler)]
The second list box binds to that collection because its <xref:System.Windows.Controls.ItemsControl.ItemsSource%2A> value is set to `{Binding}`. As a result, it displays the returned collection (based on the `myTaskTemplate` <xref:System.Windows.DataTemplate>).
## See also
- [Make Data Available for Binding in XAML](how-to-make-data-available-for-binding-in-xaml.md)
- [Bind to a Collection and Display Information Based on Selection](how-to-bind-to-a-collection-and-display-information-based-on-selection.md)
- [What's New in WPF Version 4.5](../getting-started/whats-new.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
@@ -0,0 +1,43 @@
---
title: "How to: Bind to XDocument, XElement, or LINQ for XML Query Results"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data binding [WPF], binding to XDocument"
- "data binding [WPF], binding to XElement"
ms.assetid: 6a629a49-fe1c-465d-b76a-3dcbf4307b64
---
# How to: Bind to XDocument, XElement, or LINQ for XML Query Results
This example demonstrates how to bind XML data to an <xref:System.Windows.Controls.ItemsControl> using <xref:System.Xml.Linq.XDocument>.
## Example
The following XAML code defines an <xref:System.Windows.Controls.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 <xref:System.Xml.Linq.XContainer.Element%2A> and <xref:System.Xml.Linq.XElement.Attribute%2A> methods of the <xref:System.Xml.Linq.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](linq-to-xml-dynamic-properties.md). Notice how the default namespace declaration for the XML does not apply to attribute names.
[!code-xaml[XLinqExample#StackPanelResources](~/samples/snippets/csharp/VS_Snippets_Wpf/XLinqExample/CSharp/Window1.xaml#stackpanelresources)]
[!code-xaml[XLinqExample#ItemsControl](~/samples/snippets/csharp/VS_Snippets_Wpf/XLinqExample/CSharp/Window1.xaml#itemscontrol)]
The following C# code calls <xref:System.Xml.Linq.XDocument.Load%2A> and sets the stack panel data context to all subelements of the element named `SolarSystemPlanets` in the `http://planetsNS` XML namespace.
[!code-csharp[XLinqExample#LoadDCFromFile](~/samples/snippets/csharp/VS_Snippets_Wpf/XLinqExample/CSharp/Window1.xaml.cs#loaddcfromfile)]
[!code-vb[XLinqExample#LoadDCFromFile](~/samples/snippets/visualbasic/VS_Snippets_Wpf/XLinqExample/visualbasic/window1.xaml.vb#loaddcfromfile)]
XML data can be stored as a XAML resource using <xref:System.Windows.Data.ObjectDataProvider>. For a complete example, see [L2DBForm.xaml source code](l2dbform-xaml-source-code.md). The following sample shows how code can set the data context to an object resource.
[!code-csharp[XLinqExample#LoadDCFromXAML](~/samples/snippets/csharp/VS_Snippets_Wpf/XLinqExample/CSharp/Window1.xaml.cs#loaddcfromxaml)]
[!code-vb[XLinqExample#LoadDCFromXAML](~/samples/snippets/visualbasic/VS_Snippets_Wpf/XLinqExample/visualbasic/window1.xaml.vb#loaddcfromxaml)]
The dynamic properties that map to <xref:System.Xml.Linq.XContainer.Element%2A> and <xref:System.Xml.Linq.XElement.Attribute%2A> 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.
[!code-csharp[XLinqExample#BindToResults](~/samples/snippets/csharp/VS_Snippets_Wpf/XLinqExample/CSharp/Window1.xaml.cs#bindtoresults)]
[!code-vb[XLinqExample#BindToResults](~/samples/snippets/visualbasic/VS_Snippets_Wpf/XLinqExample/visualbasic/window1.xaml.vb#bindtoresults)]
## See also
- [Binding Sources Overview](binding-sources-overview.md)
- [WPF Data Binding with LINQ to XML Overview](wpf-data-binding-with-linq-to-xml-overview.md)
- [WPF Data Binding Using LINQ to XML Example](linq-to-xml-data-binding-sample.md)
- [LINQ to XML Dynamic Properties](linq-to-xml-dynamic-properties.md)
@@ -0,0 +1,62 @@
---
title: "How to: Bind to XML Data Using an XMLDataProvider and XPath Queries"
ms.date: "03/30/2017"
helpviewer_keywords:
- "XmlDataProvider [WPF], binding to XML data"
- "data binding [WPF], binding to XML data using XmlDataProvider queries"
- "binding [WPF], to XML data using XmlDataProvider queries"
ms.assetid: 7dcd018f-16aa-4870-8e47-c1b4ea31e574
---
# How to: Bind to XML Data Using an XMLDataProvider and XPath Queries
This example shows how to bind to XML data using an <xref:System.Windows.Data.XmlDataProvider>.
With an <xref:System.Windows.Data.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 <xref:System.Windows.Data.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 <xref:System.Windows.FrameworkElement.Resources%2A> 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.
> [!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 [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] page. In this inline case, the [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)], and thus the data island, inherits the <xref:System.Windows> namespace. Because of this, you need to set the namespace blank to keep XPath queries from being qualified by the <xref:System.Windows> namespace, which would misdirect the queries.
[!code-xaml[XMLDataSource#1](~/samples/snippets/csharp/VS_Snippets_Wpf/XmlDataSource/CS/Window1.xaml#1)]
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](/dotnet/desktop-wpf/xaml-services/xml-character-entities).
The <xref:System.Windows.Controls.ListBox> will show the following items when this example is run. These are the *Title*s 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 <xref:System.Windows.Data.XmlDataProvider.XPath%2A> value set on the <xref:System.Windows.Data.XmlDataProvider> indicates that only the *Books* elements should be exposed (essentially setting a filter).
![Screenshot of the XPath example showing the title of four books.](./media/how-to-bind-to-xml-data-using-an-xmldataprovider-and-xpath-queries/xpath-example-listbox-details.png)
In this example, the book titles are displayed because the <xref:System.Windows.Data.Binding.XPath%2A> of the <xref:System.Windows.Controls.TextBlock> binding in the <xref:System.Windows.DataTemplate> is set to "*Title*". If you want to display the value of an attribute, such as the *ISBN*, you would set that <xref:System.Windows.Data.Binding.XPath%2A> value to "`@ISBN`".
The **XPath** properties in [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] are handled by the XmlNode.SelectNodes method. You can modify the **XPath** queries to get different results. Here are some examples for the <xref:System.Windows.Data.Binding.XPath%2A> query on the bound <xref:System.Windows.Controls.ListBox> from the previous example:
- `XPath="Book[1]"` will return the first book element ("XML in Action"). Note that **XPath** indexes are based on 1, not 0.
- `XPath="Book[@*]"` will return all book elements with any attributes.
- `XPath="Book[last()-1]"` will return the second to last book element ("Introducing 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 <xref:System.Xml.XmlNode> or a list of XmlNodes. <xref:System.Xml.XmlNode> is a common language runtime (CLR) object, which means you can use the <xref:System.Windows.Data.Binding.Path%2A> 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 <xref:System.Windows.Controls.TextBlock> binding to the following, you will see the names of the returned XmlNodes in the <xref:System.Windows.Controls.ListBox>. In this case, the name of all the returned nodes is "*Book*".
[!code-xaml[XmlDataSourceVariation#XmlNodePath](~/samples/snippets/csharp/VS_Snippets_Wpf/XmlDataSourceVariation/CS/Page1.xaml#xmlnodepath)]
In some applications, embedding the XML as a data island within the source of the [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] 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:
[!code-xaml[XMLDataSource2#XmlFileExample](~/samples/snippets/csharp/VS_Snippets_Wpf/XmlDataSource2/CS/Window1.xaml#xmlfileexample)]
If the XML data resides in a remote XML file, you would define access to the data by assigning an appropriate URL to the <xref:System.Windows.Data.XmlDataProvider.Source%2A> attribute as follows:
```xml
<XmlDataProvider x:Key="BookData" Source="http://MyUrl" XPath="Books"/>
```
## See also
- <xref:System.Windows.Data.ObjectDataProvider>
- [Bind to XDocument, XElement, or LINQ for XML Query Results](how-to-bind-to-xdocument-xelement-or-linq-for-xml-query-results.md)
- [Use the Master-Detail Pattern with Hierarchical XML Data](how-to-use-the-master-detail-pattern-with-hierarchical-xml-data.md)
- [Binding Sources Overview](binding-sources-overview.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,30 @@
---
title: "How to: Clear Bindings"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "bindings [WPF], clearing"
- "clearing bindings [WPF]"
- "data binding [WPF], clearing bindings"
ms.assetid: 73962a93-32a9-4bcd-9240-bcfbb239093a
---
# How to: Clear Bindings
This example shows how to clear bindings from an object.
## Example
To clear a binding from an individual property on an object, call <xref:System.Windows.Data.BindingOperations.ClearBinding%2A> as shown in the following example. The following example removes the binding from the <xref:System.Windows.Controls.TextBlock.TextProperty> of *mytext*, a <xref:System.Windows.Controls.TextBlock> object.
[!code-csharp[CodeOnlyBinding#ClearBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/CodeOnlyBinding/CSharp/binding.cs#clearbinding)]
[!code-vb[CodeOnlyBinding#ClearBinding](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CodeOnlyBinding/VisualBasic/App.vb#clearbinding)]
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.
To clear bindings from all possible properties on an object, use <xref:System.Windows.Data.BindingOperations.ClearAllBindings%2A>.
## See also
- <xref:System.Windows.Data.BindingOperations>
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,45 @@
---
title: "How to: Control When the TextBox Text Updates the Source"
description: Control the timing of binding source updates using the UpdateSourceTrigger property in Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "source updates [WPF], timing of"
- "data binding [WPF], timing of source updates"
- "timing of source updates [WPF]"
ms.assetid: ffb7b96a-351d-4c68-81e7-054033781c64
---
# How to: Control When the TextBox Text Updates the Source
This topic describes how to use the <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> property to control the timing of binding source updates. The topic uses the <xref:System.Windows.Controls.TextBox> control as an example.
## Example
The <xref:System.Windows.Controls.TextBox.Text%2A?displayProperty=nameWithType> property has a default <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> value of <xref:System.Windows.Data.UpdateSourceTrigger.LostFocus>. This means if an application has a <xref:System.Windows.Controls.TextBox> with a data-bound <xref:System.Windows.Controls.TextBox.Text%2A?displayProperty=nameWithType> property, the text you type into the <xref:System.Windows.Controls.TextBox> does not update the source until the <xref:System.Windows.Controls.TextBox> loses focus (for instance, when you click away from the <xref:System.Windows.Controls.TextBox>).
If you want the source to be updated as you type, set the <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> of the binding to <xref:System.Windows.Data.UpdateSourceTrigger.PropertyChanged>. In the following example, the highlighted lines of code show that the `Text` properties of both the <xref:System.Windows.Controls.TextBox> and the <xref:System.Windows.Controls.TextBlock> are bound to the same source property. The <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> property of the <xref:System.Windows.Controls.TextBox> binding is set to <xref:System.Windows.Data.UpdateSourceTrigger.PropertyChanged>.
[!code-xaml[SimpleBinding#USTHowTo](~/samples/snippets/visualbasic/VS_Snippets_Wpf/SimpleBinding/VisualBasic/Page1.xaml?highlight=33-39,41-42)]
As a result, the <xref:System.Windows.Controls.TextBlock> shows the same text (because the source changes) as the user enters text into the <xref:System.Windows.Controls.TextBox>, as illustrated by the following screenshot of the sample:
![Screenshot that shows simple data binding.](./media/how-to-control-when-the-textbox-text-updates-the-source/data-binding-simple-binding-sample.png)
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 <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> value of your bindings to <xref:System.Windows.Data.UpdateSourceTrigger.Explicit>, as in the following example:
[!code-xaml[UpdateSource#2](~/samples/snippets/csharp/VS_Snippets_Wpf/UpdateSource/CSharp/Window1.xaml#2)]
When you set the <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> value to <xref:System.Windows.Data.UpdateSourceTrigger.Explicit>, the source value only changes when the application calls the <xref:System.Windows.Data.BindingExpression.UpdateSource%2A> method. The following example shows how to call <xref:System.Windows.Data.BindingExpression.UpdateSource%2A> for `itemNameTextBox`:
[!code-csharp[UpdateSource#1](~/samples/snippets/csharp/VS_Snippets_Wpf/UpdateSource/CSharp/Window1.xaml.cs#1)]
[!code-vb[UpdateSource#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/UpdateSource/VisualBasic/Window1.xaml.vb#1)]
> [!NOTE]
> You can use the same technique for properties of other controls, but keep in mind that most other properties have a default <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> value of <xref:System.Windows.Data.UpdateSourceTrigger.PropertyChanged>. For more information, see the <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> property page.
> [!NOTE]
> The <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> property deals with source updates and therefore is only relevant for <xref:System.Windows.Data.BindingMode.TwoWay> or <xref:System.Windows.Data.BindingMode.OneWayToSource> bindings. For <xref:System.Windows.Data.BindingMode.TwoWay> and <xref:System.Windows.Data.BindingMode.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](how-to-implement-property-change-notification.md).
## See also
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,38 @@
---
title: "How to: Convert Bound Data"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "converting [WPF], bound data"
- "data binding [WPF], converting bound data"
- "binding data [WPF], converting bound data"
ms.assetid: b00aaa19-c6df-4c3b-a9fd-88a0b488df2b
---
# How to: Convert Bound Data
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 <xref:System.Windows.Data.IValueConverter> interface, which includes the <xref:System.Windows.Data.IValueConverter.Convert%2A> and <xref:System.Windows.Data.IValueConverter.ConvertBack%2A> 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 <xref:System.Windows.Data.IValueConverter> interface, it is a good practice to decorate the implementation with a <xref:System.Windows.Data.ValueConversionAttribute> attribute to indicate to development tools the data types involved in the conversion, as in the following example:
[!code-csharp[DataBindingLab#18](~/samples/snippets/csharp/VS_Snippets_Wpf/DataBindingLab/CSharp/DateConverter.cs#18)]
[!code-vb[DataBindingLab#18](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DataBindingLab/VisualBasic/DateConverter.vb#18)]
Once you have created a converter, you can add it as a resource in your [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)] file. In the following example, *src* maps to the namespace in which *DateConverter* is defined.
[!code-xaml[DataBindingLab#15](~/samples/snippets/csharp/VS_Snippets_Wpf/DataBindingLab/CSharp/DataBindingLabApp.xaml#15)]
Finally, you can use the converter in your binding using the following syntax. In the following example, the text content of the <xref:System.Windows.Controls.TextBlock> is bound to *StartDate*, which is a property of an external data source.
[!code-xaml[DataBindingLab#17](~/samples/snippets/csharp/VS_Snippets_Wpf/DataBindingLab/CSharp/DataBindingLabApp.xaml#17)]
The style resources referenced in the above example are defined in a resource section not shown in this topic.
## See also
- [Implement Binding Validation](how-to-implement-binding-validation.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,39 @@
---
title: "How to: Create a Binding in Code"
description: Learn how to create a binding in code in a Windows Presentation Foundation application by calling the SetBinding method directly.
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "binding data [WPF], creating"
- "data binding [WPF], creating"
ms.assetid: 1a606db9-cf5f-42ed-a1c5-9e4722ec77a0
---
# How to: Create a Binding in Code
This example shows how to create and set a <xref:System.Windows.Data.Binding> in code.
## Example
The <xref:System.Windows.FrameworkElement> class and the <xref:System.Windows.FrameworkContentElement> class both expose a `SetBinding` method. If you are binding an element that inherits either of these classes, you can call the <xref:System.Windows.FrameworkElement.SetBinding%2A> method directly.
The following example creates a class named, `MyData`, which contains a property named `MyDataProperty`.
[!code-csharp[CodeOnlyBinding#DataObject](~/samples/snippets/csharp/VS_Snippets_Wpf/CodeOnlyBinding/CSharp/MyData.cs#dataobject)]
[!code-vb[CodeOnlyBinding#DataObject](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CodeOnlyBinding/VisualBasic/MyData.vb#dataobject)]
The following example shows how to create a binding object to set the source of the binding. The example uses <xref:System.Windows.FrameworkElement.SetBinding%2A> to bind the <xref:System.Windows.Controls.TextBlock.Text%2A> property of `myText`, which is a <xref:System.Windows.Controls.TextBlock> control, to `MyDataProperty`.
[!code-csharp[CodeOnlyBinding#1](~/samples/snippets/csharp/VS_Snippets_Wpf/CodeOnlyBinding/CSharp/binding.cs#1)]
[!code-vb[CodeOnlyBinding#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CodeOnlyBinding/VisualBasic/App.vb#1)]
For the complete code sample, see [Code-only Binding Sample](https://docs.microsoft.com/previous-versions/dotnet/netframework-3.5/ms771500(v=vs.90)).
Instead of calling <xref:System.Windows.FrameworkElement.SetBinding%2A>, you can use the <xref:System.Windows.Data.BindingOperations.SetBinding%2A> static method of the <xref:System.Windows.Data.BindingOperations> class. The following example, calls <xref:System.Windows.Data.BindingOperations.SetBinding%2A?displayProperty=nameWithType> instead of <xref:System.Windows.FrameworkElement.SetBinding%2A?displayProperty=nameWithType> to bind `myText` to `myDataProperty`.
[!code-csharp[CodeOnlyBinding#BOSetBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/CodeOnlyBinding/CSharp/binding.cs#bosetbinding)]
[!code-vb[CodeOnlyBinding#BOSetBinding](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CodeOnlyBinding/VisualBasic/App.vb#bosetbinding)]
## See also
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,26 @@
---
title: "How to: Create a Simple Binding"
description: Create a simple binding for your applications through this how-to example in Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
helpviewer_keywords:
- "simple binding [WPF], creating"
- "data binding [WPF], creating simple bindings"
- "binding data [WPF], creating"
ms.assetid: 69b80f72-6259-44cb-8294-5bdcebca1e08
---
# How to: Create a Simple Binding
This example shows you how to create a simple <xref:System.Windows.Data.Binding>.
## Example
In this example, you have a `Person` object with a string property named `PersonName`. The `Person` object is defined in the namespace called `SDKSample`.
The highlighted line that contains the `<src>` element in the following example instantiates the `Person` object with a `PersonName` property value of `Joe`. This is done in the `Resources` section and assigned an `x:Key`.
[!code-xaml[SimpleBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/SimpleBinding/CSharp/Page1.xaml?highlight=9,37)]
The highlighted line that contains the `<TextBlock>` element then binds the <xref:System.Windows.Controls.TextBlock> control to the `PersonName` property. As a result, the <xref:System.Windows.Controls.TextBlock> appears with the value "Joe".
## See also
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,144 @@
---
title: "How to: Create and Bind to an ObservableCollection"
description: Find out how to create and bind to a collection that derives from the ObservableCollection class in Windows Presentation Foundation.
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data binding [WPF], ObservableCollection class"
- "notifications [WPF]"
ms.assetid: 6cf7e275-df76-41c6-a611-53b889b8fd5a
---
# How to: Create and Bind to an ObservableCollection
This example shows how to create and bind to a collection that derives from the <xref:System.Collections.ObjectModel.ObservableCollection%601> 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:
```csharp
public class NameList : ObservableCollection<PersonName>
{
public NameList() : base()
{
Add(new PersonName("Willa", "Cather"));
Add(new PersonName("Isak", "Dinesen"));
Add(new PersonName("Victor", "Hugo"));
Add(new PersonName("Jules", "Verne"));
}
}
public class PersonName
{
private string firstName;
private string lastName;
public PersonName(string first, string last)
{
this.firstName = first;
this.lastName = last;
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
```
```vb
Public Class NameList
Inherits ObservableCollection(Of PersonName)
' Methods
Public Sub New()
MyBase.Add(New PersonName("Willa", "Cather"))
MyBase.Add(New PersonName("Isak", "Dinesen"))
MyBase.Add(New PersonName("Victor", "Hugo"))
MyBase.Add(New PersonName("Jules", "Verne"))
End Sub
End Class
Public Class PersonName
' Methods
Public Sub New(ByVal first As String, ByVal last As String)
Me._firstName = first
Me._lastName = last
End Sub
' Properties
Public Property FirstName() As String
Get
Return Me._firstName
End Get
Set(ByVal value As String)
Me._firstName = value
End Set
End Property
Public Property LastName() As String
Get
Return Me._lastName
End Get
Set(ByVal value As String)
Me._lastName = value
End Set
End Property
' Fields
Private _firstName As String
Private _lastName As String
End Class
```
You can make the collection available for binding the same way you would with other common language runtime (CLR) objects, as described in [Make Data Available for Binding in XAML](how-to-make-data-available-for-binding-in-xaml.md). For example, you can instantiate the collection in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)] and specify the collection as a resource, as shown here:
```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>
```
You can then bind to the collection:
```xaml
<ListBox Width="200"
ItemsSource="{Binding Source={StaticResource NameListData}}"
ItemTemplate="{StaticResource NameItemTemplate}"
IsSynchronizedWithCurrentItem="True"/>
```
The definition of `NameItemTemplate` is not shown here.
> [!NOTE]
> The objects in your collection must satisfy the requirements described in the [Binding Sources Overview](binding-sources-overview.md). In particular, if you are using <xref:System.Windows.Data.BindingMode.OneWay> or <xref:System.Windows.Data.BindingMode.TwoWay> (for example, you want your [!INCLUDE[TLA2#tla_ui](../../../includes/tla2sharptla-ui-md.md)] to update when the source properties change dynamically), you must implement a suitable property changed notification mechanism such as the <xref:System.ComponentModel.INotifyPropertyChanged> interface.
For more information, see the Binding to Collections section in the [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview).
## See also
- [Sort Data in a View](how-to-sort-data-in-a-view.md)
- [Filter Data in a View](how-to-filter-data-in-a-view.md)
- [Sort and Group Data Using a View in XAML](how-to-sort-and-group-data-using-a-view-in-xaml.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,50 @@
---
title: "How to: Filter Data in a View"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "views [WPF], filtering data"
- "filtering data in views [WPF]"
- "data binding [WPF], filtering data in views"
ms.assetid: c76e8606-4cc4-45a8-9110-e2ec66dc6afd
---
# How to: Filter Data in a View
This example shows how to filter data in a view.
## 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.
[!code-csharp[SortFilter#2](~/samples/snippets/csharp/VS_Snippets_Wpf/SortFilter/CSharp/Page1.xaml.cs#2)]
[!code-vb[SortFilter#2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/SortFilter/VisualBasic/Page1.xaml.vb#2)]
You can then apply the filter, as shown in the following example. In this example, `myCollectionView` is a <xref:System.Windows.Data.ListCollectionView> object.
[!code-csharp[SortFilter#Filter](~/samples/snippets/csharp/VS_Snippets_Wpf/SortFilter/CSharp/Page1.xaml.cs#filter)]
[!code-vb[SortFilter#Filter](~/samples/snippets/visualbasic/VS_Snippets_Wpf/SortFilter/VisualBasic/Page1.xaml.vb#filter)]
To undo filtering, you can set the <xref:System.Windows.Data.CollectionView.Filter%2A> property to `null`:
[!code-csharp[SortFilter#Unfilter](~/samples/snippets/csharp/VS_Snippets_Wpf/SortFilter/CSharp/Page1.xaml.cs#unfilter)]
[!code-vb[SortFilter#Unfilter](~/samples/snippets/visualbasic/VS_Snippets_Wpf/SortFilter/VisualBasic/Page1.xaml.vb#unfilter)]
For information about how to create or obtain a view, see [Get the Default View of a Data Collection](how-to-get-the-default-view-of-a-data-collection.md). For the complete example, see [Sorting and Filtering Items in a View Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Data%20Binding/SortFilter).
If your view object comes from a <xref:System.Windows.Data.CollectionViewSource> object, you apply filtering logic by setting an event handler for the <xref:System.Windows.Data.CollectionViewSource.Filter> event. In the following example, `listingDataView` is an instance of <xref:System.Windows.Data.CollectionViewSource>.
[!code-csharp[DataBindingLab#10](~/samples/snippets/csharp/VS_Snippets_Wpf/DataBindingLab/CSharp/MainWindow.xaml.cs#10)]
[!code-vb[DataBindingLab#10](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DataBindingLab/VisualBasic/MainWindow.xaml.vb#10)]
The following shows the implementation of the example `ShowOnlyBargainsFilter` filter event handler. This event handler uses the <xref:System.Windows.Data.FilterEventArgs.Accepted%2A> property to filter out `AuctionItem` objects that have a `CurrentPrice` of $25 or greater.
[!code-csharp[DataBindingLab#5](~/samples/snippets/csharp/VS_Snippets_Wpf/DataBindingLab/CSharp/MainWindow.xaml.cs#5)]
[!code-vb[DataBindingLab#5](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DataBindingLab/VisualBasic/MainWindow.xaml.vb#5)]
## See also
- <xref:System.Windows.Data.CollectionView.CanFilter%2A>
- <xref:System.Windows.Data.BindingListCollectionView.CustomFilter%2A>
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [Sort Data in a View](how-to-sort-data-in-a-view.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,41 @@
---
title: "How to: Find DataTemplate-Generated Elements"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "finding DataTemplate elements [WPF]"
- "DataTemplate [WPF]"
ms.assetid: bfcd564e-5e9e-451e-8641-a9b5c3cfac90
---
# How to: Find DataTemplate-Generated Elements
This example shows how to find elements that are generated by a <xref:System.Windows.DataTemplate>.
## Example
In this example, there is a <xref:System.Windows.Controls.ListBox> that is bound to some XML data:
[!code-xaml[FindGeneratedItems#LB](~/samples/snippets/csharp/VS_Snippets_Wpf/FindGeneratedItems/CSharp/Window1.xaml#lb)]
The <xref:System.Windows.Controls.ListBox> uses the following <xref:System.Windows.DataTemplate>:
[!code-xaml[FindGeneratedItems#DT](~/samples/snippets/csharp/VS_Snippets_Wpf/FindGeneratedItems/CSharp/Window1.xaml#dt)]
If you want to retrieve the <xref:System.Windows.Controls.TextBlock> element generated by the <xref:System.Windows.DataTemplate> of a certain <xref:System.Windows.Controls.ListBoxItem>, you need to get the <xref:System.Windows.Controls.ListBoxItem>, find the <xref:System.Windows.Controls.ContentPresenter> within that <xref:System.Windows.Controls.ListBoxItem>, and then call <xref:System.Windows.FrameworkTemplate.FindName%2A> on the <xref:System.Windows.DataTemplate> that is set on that <xref:System.Windows.Controls.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 <xref:System.Windows.DataTemplate>-generated text block.
[!code-csharp[FindGeneratedItems#DTFindElement](~/samples/snippets/csharp/VS_Snippets_Wpf/FindGeneratedItems/CSharp/Window1.xaml.cs#dtfindelement)]
[!code-vb[FindGeneratedItems#DTFindElement](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FindGeneratedItems/VisualBasic/Window1.xaml.vb#dtfindelement)]
The following is the implementation of `FindVisualChild`, which uses the <xref:System.Windows.Media.VisualTreeHelper> methods:
[!code-csharp[FindGeneratedItems#FVC](~/samples/snippets/csharp/VS_Snippets_Wpf/FindGeneratedItems/CSharp/Window1.xaml.cs#fvc)]
[!code-vb[FindGeneratedItems#FVC](~/samples/snippets/visualbasic/VS_Snippets_Wpf/FindGeneratedItems/VisualBasic/Window1.xaml.vb#fvc)]
## See also
- [How to: Find ControlTemplate-Generated Elements](../controls/how-to-find-controltemplate-generated-elements.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
- [Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview)
- [WPF XAML Namescopes](../advanced/wpf-xaml-namescopes.md)
- [Trees in WPF](../advanced/trees-in-wpf.md)
@@ -0,0 +1,30 @@
---
title: "How to: Get the Binding Object from a Bound Target Property"
ms.date: "03/30/2017"
helpviewer_keywords:
- "data binding [WPF], getting binding objects from bound target properties"
- "properties [WPF], getting binding objects from"
ms.assetid: 87974c5f-136b-4de7-b07d-9285b62ab123
---
# How to: Get the Binding Object from a Bound Target Property
This example shows how to obtain the binding object from a data-bound target property.
## Example
You can do the following to get the <xref:System.Windows.Data.Binding> object:
[!code-csharp[BindValidation#GetBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml.cs#getbinding)]
> [!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 <xref:System.Windows.Data.BindingExpression> and then get the value of the <xref:System.Windows.Data.BindingExpression.ParentBinding%2A> property.
For the complete example see [Binding Validation Sample](https://github.com/Microsoft/WPF-Samples/tree/master/Data%20Binding/BindValidation).
> [!NOTE]
> If your binding is a <xref:System.Windows.Data.MultiBinding>, use <xref:System.Windows.Data.BindingOperations.GetMultiBinding%2A?displayProperty=nameWithType>. If it is a <xref:System.Windows.Data.PriorityBinding>, use <xref:System.Windows.Data.BindingOperations.GetPriorityBinding%2A?displayProperty=nameWithType>. If you are uncertain whether the target property is bound using a <xref:System.Windows.Data.Binding>, a <xref:System.Windows.Data.MultiBinding>, or a <xref:System.Windows.Data.PriorityBinding>, you can use <xref:System.Windows.Data.BindingOperations.GetBindingBase%2A?displayProperty=nameWithType>.
## See also
- [Create a Binding in Code](how-to-create-a-binding-in-code.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,32 @@
---
title: "How to: Get the Default View of a Data Collection"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data collections [WPF], creating views of"
- "data binding [WPF], creating views of data collections"
ms.assetid: b641e96c-c2f6-42ea-9c5d-bac81176ad65
---
# How to: Get the Default View of a Data Collection
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 <xref:System.Windows.FrameworkElement.DataContext%2A> of a data object and use it to directly obtain the default collection view for this collection.
[!code-csharp[CollectionView#2](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionView/CSharp/Page1.xaml.cs#2)]
[!code-vb[CollectionView#2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CollectionView/VisualBasic/Page1.xaml.vb#2)]
In this example, the root element is a <xref:System.Windows.Controls.StackPanel>. The <xref:System.Windows.FrameworkElement.DataContext%2A> is set to *myDataSource*, which refers to a data provider that is an <xref:System.Collections.ObjectModel.ObservableCollection%601> of *Order* objects.
[!code-xaml[CollectionView#CollectionViewDataContext](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionView/CSharp/Page1.xaml#collectionviewdatacontext)]
Alternatively, you can instantiate and bind to your own collection view using the <xref:System.Windows.Data.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](/dotnet/desktop-wpf/data/data-binding-overview).
For examples of the functionality provided by a collection view, see [Sort Data in a View](how-to-sort-data-in-a-view.md), [Filter Data in a View](how-to-filter-data-in-a-view.md), and [Navigate Through the Objects in a Data CollectionView](how-to-navigate-through-the-objects-in-a-data-collectionview.md).
## See also
- [Sort and Group Data Using a View in XAML](how-to-sort-and-group-data-using-a-view-in-xaml.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,21 @@
---
title: "How to: Implement a CompositeCollection"
ms.date: "03/30/2017"
helpviewer_keywords:
- "data binding [WPF], CompositeCollection class"
ms.assetid: 0d8fc84c-7920-427f-8ad7-d55ca656c170
---
# How to: Implement a CompositeCollection
## Example
The following example shows how to display multiple collections and items as one list using the <xref:System.Windows.Data.CompositeCollection> class. In this example, `GreekGods` is an <xref:System.Collections.ObjectModel.ObservableCollection%601> of `GreekGod` custom objects. Data templates are defined so that `GreekGod` objects and `GreekHero` objects appear with a gold and a cyan foreground color respectively.
[!code-xaml[CompositeCollections#1](~/samples/snippets/csharp/VS_Snippets_Wpf/CompositeCollections/CS/Window1.xaml#1)]
## See also
- <xref:System.Windows.Data.CollectionContainer>
- <xref:System.Windows.Controls.ItemsControl.ItemsSource%2A>
- <xref:System.Windows.Data.XmlDataProvider>
- <xref:System.Windows.DataTemplate>
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,44 @@
---
title: "How to: Implement Binding Validation"
description: Learn how to using binding validation to provide visual feedback to the user when an invalid value is entered in Windows Presentation Foundation (WPF).
ms.date: 03/30/2017
dev_langs:
- csharp
- vb
helpviewer_keywords:
- "validation of binding [WPF]"
- "data binding [WPF], validation of binding"
- "binding [WPF], validation of"
ms.assetid: eb98b33d-9866-49ae-b981-bc5ff20d607a
---
# How to: Implement Binding Validation
This example shows how to use an <xref:System.Windows.Controls.Validation.ErrorTemplate%2A> 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 <xref:System.Windows.Controls.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.
[!code-xaml[BindValidation#2](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#2)]
The following example shows the implementation of `AgeRangeRule`, which inherits from <xref:System.Windows.Controls.ValidationRule> and overrides the <xref:System.Windows.Controls.ValidationRule.Validate%2A> method. The `Int32.Parse` method is called on the value to make sure that it does not contain any invalid characters. The <xref:System.Windows.Controls.ValidationRule.Validate%2A> method returns a <xref:System.Windows.Controls.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.
[!code-csharp[BindValidation#3](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/AgeRangeRule.cs#3)]
[!code-vb[BindValidation#3](~/samples/snippets/visualbasic/VS_Snippets_Wpf/BindValidation/VisualBasic/AgeRangeRule.vb#3)]
The following example shows the custom <xref:System.Windows.Controls.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.
[!code-xaml[BindValidation#4](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#4)]
As shown in the following example, the <xref:System.Windows.Controls.ToolTip> that shows the error message is created using the style named `textBoxInError`. If the value of <xref:System.Windows.Controls.Validation.HasError%2A> is `true`, the trigger sets the tool tip of the current <xref:System.Windows.Controls.TextBox> to its first validation error. The <xref:System.Windows.Data.Binding.RelativeSource%2A> is set to <xref:System.Windows.Data.RelativeSourceMode.Self>, referring to the current element.
[!code-xaml[BindValidation#5](~/samples/snippets/csharp/VS_Snippets_Wpf/BindValidation/CSharp/Window1.xaml#5)]
For the complete example, see [Bind Validation sample](https://github.com/Microsoft/WPF-Samples/tree/master/Data%20Binding/BindValidation).
Note that if you do not provide a custom <xref:System.Windows.Controls.Validation.ErrorTemplate%2A> 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](/dotnet/desktop-wpf/data/data-binding-overview) for more information. Also, [!INCLUDE[TLA2#tla_winclient](../../../includes/tla2sharptla-winclient-md.md)] provides a built-in validation rule that catches exceptions that are thrown during the update of the binding source property. For more information, see <xref:System.Windows.Controls.ExceptionValidationRule>.
## See also
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,45 @@
---
title: "How to: Implement PriorityBinding"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data binding [WPF], PriorityBinding class"
ms.assetid: d63b65ab-b3e9-4322-9aa8-1450f8d89532
---
# How to: Implement PriorityBinding
<xref:System.Windows.Data.PriorityBinding> in [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] works by specifying a list of bindings. The list of bindings is ordered from highest priority to lowest priority. If the highest priority binding returns a value successfully when it is processed then there is never a need to process the other bindings in the list. It could be the case that the highest priority binding takes a long time to be evaluated, the next highest priority that returns a value successfully will be used until a binding of a higher priority returns a value successfully.
## Example
To demonstrate how <xref:System.Windows.Data.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.
> [!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](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ms229054(v=vs.100)).
[!code-csharp[PriorityBinding#1](~/samples/snippets/csharp/VS_Snippets_Wpf/PriorityBinding/CSharp/Window1.xaml.cs#1)]
[!code-vb[PriorityBinding#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/PriorityBinding/VisualBasic/AsyncDataSource.vb#1)]
The <xref:System.Windows.Controls.TextBlock.Text%2A> property binds to the above `AsyncDS` using <xref:System.Windows.Data.PriorityBinding>:
[!code-xaml[PriorityBinding#2](~/samples/snippets/csharp/VS_Snippets_Wpf/PriorityBinding/CSharp/Window1.xaml#2)]
When the binding engine processes the <xref:System.Windows.Data.Binding> objects, it starts with the first <xref:System.Windows.Data.Binding>, which is bound to the `SlowestDP` property. When this <xref:System.Windows.Data.Binding> is processed, it does not return a value successfully because it is sleeping for 5 seconds, so the next <xref:System.Windows.Data.Binding> element is processed. The next <xref:System.Windows.Data.Binding> does not return a value successfully because it is sleeping for 3 seconds. The binding engine then moves onto the next <xref:System.Windows.Data.Binding> element, which is bound to the `FastDP` property. This <xref:System.Windows.Data.Binding> returns the value "Fast Value". The <xref:System.Windows.Controls.TextBlock> now displays the value "Fast Value".
After 3 seconds elapses, the `SlowerDP` property returns the value "Slower Value". The <xref:System.Windows.Controls.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 <xref:System.Windows.Controls.TextBlock> now displays the value "Slowest Value".
See <xref:System.Windows.Data.PriorityBinding> for information about what is considered a successful return value from a binding.
## See also
- <xref:System.Windows.Data.Binding.IsAsync%2A?displayProperty=nameWithType>
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,30 @@
---
title: "How to: Implement Property Change Notification"
description: Enable your properties to automatically notify a binding source when the property value changes in Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "notifications of change [WPF]"
- "data binding [WPF], property change notifications"
- "change notifications [WPF]"
- "properties [WPF], change notifications"
ms.assetid: 30b59d9e-8c3a-4349-aa82-4be837e841cf
---
# How to: Implement Property Change Notification
To support <xref:System.Windows.Data.BindingMode.OneWay> or <xref:System.Windows.Data.BindingMode.TwoWay> binding to enable your binding target properties to automatically reflect the dynamic changes of the binding source (for example, to have the preview pane updated automatically when the user edits a form), your class needs to provide the proper property changed notifications. This example shows how to create a class that implements <xref:System.ComponentModel.INotifyPropertyChanged>.
## Example
To implement <xref:System.ComponentModel.INotifyPropertyChanged> you need to declare the <xref:System.ComponentModel.INotifyPropertyChanged.PropertyChanged> event and create the `OnPropertyChanged` method. Then for each property you want change notifications for, you call `OnPropertyChanged` whenever the property is updated.
[!code-csharp[SimpleBinding#PersonClass](~/samples/snippets/csharp/VS_Snippets_Wpf/SimpleBinding/CSharp/Person.cs#personclass)]
[!code-vb[SimpleBinding#PersonClass](~/samples/snippets/visualbasic/VS_Snippets_Wpf/SimpleBinding/VisualBasic/Person.vb#personclass)]
To see an example of how the `Person` class can be used to support <xref:System.Windows.Data.BindingMode.TwoWay> binding, see [Control When the TextBox Text Updates the Source](how-to-control-when-the-textbox-text-updates-the-source.md).
## See also
- [Binding Sources Overview](binding-sources-overview.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,33 @@
---
title: "How to: Implement Validation Logic on Custom Objects"
ms.date: "08/02/2018"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "checking for validation errors [WPF]"
- "validation errors [WPF], checking for"
- "implementing validation logic on custom objects [WPF]"
- "custom objects [WPF], implementing validation logic on"
ms.assetid: 751fda9b-44f9-4d63-b4f2-1df07ac41e0f
---
# How to: Implement Validation Logic on Custom Objects
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 <xref:System.ComponentModel.IDataErrorInfo>, as in the following example, which defines a `Person` object that implements <xref:System.ComponentModel.IDataErrorInfo>:
[!code-csharp[BusinessLayerValidation#IDataErrorInfo](~/samples/snippets/csharp/VS_Snippets_Wpf/BusinessLayerValidation/CSharp/Data.cs#idataerrorinfo)]
[!code-vb[BusinessLayerValidation#IDataErrorInfo](~/samples/snippets/visualbasic/VS_Snippets_Wpf/BusinessLayerValidation/VisualBasic/Data.vb#idataerrorinfo)]
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 <xref:System.Windows.Controls.DataErrorValidationRule> checks for the validation errors raised by the <xref:System.ComponentModel.IDataErrorInfo> implementation.
[!code-xaml[BusinessLayerValidation#BoundTextBox](~/samples/snippets/csharp/VS_Snippets_Wpf/BusinessLayerValidation/CSharp/Window1.xaml?highlight=8,11-19,25-42)]
Alternatively, instead of using the <xref:System.Windows.Controls.DataErrorValidationRule>, you can set the <xref:System.Windows.Data.Binding.ValidatesOnDataErrors%2A> property to `true`.
## See also
- <xref:System.Windows.Controls.ExceptionValidationRule>
- [Implement Binding Validation](how-to-implement-binding-validation.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,43 @@
---
title: "How to: Make Data Available for Binding in XAML"
description: Discover the various ways you can make data available according to the needs of your application in Windows Presentation Foundation (WPF).
ms.date: "01/29/2018"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data binding [WPF], making data available for binding"
- "binding data [WPF], making data available for"
ms.assetid: 7103c2e8-0e31-4a13-bf12-ca382221a8d5
---
# How to: Make Data Available for Binding in XAML
This topic discusses various ways you can make data available for binding in [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)], depending on the needs of your application.
## Example
If you have a common language runtime (CLR) object you would like to bind to from [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)], 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) is defined in the namespace called `SDKSample`.
[!code-xaml[SimpleBinding#Instantiation](~/samples/snippets/csharp/VS_Snippets_Wpf/SimpleBinding/CSharp/Page1.xaml?highlight=9,37)]
You can then bind the <xref:System.Windows.Controls.TextBlock> control to the object in [!INCLUDE[TLA2#tla_xaml](../../../includes/tla2sharptla-xaml-md.md)], as the highlighted line that contains the `<TextBlock>` element shows.
Alternatively, you can use the <xref:System.Windows.Data.ObjectDataProvider> class, as in the following example:
[!code-xaml[ObjectDataProvider}](~/samples/snippets/visualbasic/VS_Snippets_Wpf/SimpleBinding/VisualBasic/Page1.xaml?highlight=10-14,42)]
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 <xref:System.Windows.Controls.TextBlock> with the text content `Joe`. However, the <xref:System.Windows.Data.ObjectDataProvider> class provides functionality such as the ability to bind to the result of a method. You can choose to use the <xref:System.Windows.Data.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.
[!code-csharp[ADODataSet#1](~/samples/snippets/csharp/VS_Snippets_Wpf/ADODataSet/CSharp/Window1.xaml.cs#1)]
[!code-vb[ADODataSet#1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/ADODataSet/VisualBasic/Window1.xaml.vb#1)]
To access XML data for binding using the <xref:System.Windows.Data.XmlDataProvider> class, see [Bind to XML Data Using an XMLDataProvider and XPath Queries](how-to-bind-to-xml-data-using-an-xmldataprovider-and-xpath-queries.md). To access XML data for binding using the <xref:System.Windows.Data.ObjectDataProvider> class, see [Bind to XDocument, XElement, or LINQ for XML Query Results](how-to-bind-to-xdocument-xelement-or-linq-for-xml-query-results.md).
For information about many ways you can specify the data you are binding to, see [Specify the Binding Source](how-to-specify-the-binding-source.md). 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](binding-sources-overview.md).
## See also
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,32 @@
---
title: "How to: Navigate Through the Objects in a Data CollectionView"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "CollectionView [WPF], navigating through objects"
- "data binding [WPF], navigating through objects in data CollectionView"
- "navigating through objects in data CollectionView [WPF]"
ms.assetid: fcd37590-bce1-4ac9-8b74-3b96c7458b8a
---
# How to: Navigate Through the Objects in a Data CollectionView
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 <xref:System.Windows.Data.CollectionView> class.
## Example
In this example, `myCollectionView` is a <xref:System.Windows.Data.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 <xref:System.Windows.Data.CollectionView.IsCurrentBeforeFirst%2A> and <xref:System.Windows.Data.CollectionView.IsCurrentAfterLast%2A> properties report whether the current record pointer has come to the beginning and the end of the list respectively so that <xref:System.Windows.Data.CollectionView.MoveCurrentToFirst%2A> and <xref:System.Windows.Data.CollectionView.MoveCurrentToLast%2A> can be called as appropriately.
The <xref:System.Windows.Data.CollectionView.CurrentItem%2A> property of the view is cast as an `Order` to return the current order item in the collection.
[!code-csharp[CollectionView#OnButton](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionView/CSharp/Page1.xaml.cs#onbutton)]
[!code-vb[CollectionView#OnButton](~/samples/snippets/visualbasic/VS_Snippets_Wpf/CollectionView/VisualBasic/Page1.xaml.vb#onbutton)]
## See also
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [Sort Data in a View](how-to-sort-data-in-a-view.md)
- [Filter Data in a View](how-to-filter-data-in-a-view.md)
- [Sort and Group Data Using a View in XAML](how-to-sort-and-group-data-using-a-view-in-xaml.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,34 @@
---
title: "How to: Produce a Value Based on a List of Bound Items"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data binding [WPF], MultiBinding"
- "Multibinding [WPF]"
ms.assetid: b3d06378-b511-4181-95aa-316d60c9229b
---
# How to: Produce a Value Based on a List of Bound Items
<xref:System.Windows.Data.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 <xref:System.Windows.Data.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 <xref:System.Windows.Controls.TextBlock> that shows the first and last names of a person with the last name first.
[!code-xaml[MultiBinding#Resources1](~/samples/snippets/csharp/VS_Snippets_Wpf/MultiBinding/CSharp/Window1.xaml#resources1)]
[!code-xaml[MultiBinding#Resources2](~/samples/snippets/csharp/VS_Snippets_Wpf/MultiBinding/CSharp/Window1.xaml#resources2)]
[!code-xaml[MultiBinding#MultiBindingTextBox2](~/samples/snippets/csharp/VS_Snippets_Wpf/MultiBinding/CSharp/Window1.xaml#multibindingtextbox2)]
[!code-xaml[MultiBinding#Window](~/samples/snippets/csharp/VS_Snippets_Wpf/MultiBinding/CSharp/Window1.xaml#window)]
To understand how the last-name-first format is produced, let's take a look at the implementation of the `NameConverter`:
[!code-csharp[MultiBinding#3](~/samples/snippets/csharp/VS_Snippets_Wpf/MultiBinding/CSharp/NameConverter.cs#3)]
[!code-vb[MultiBinding#3](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MultiBinding/VisualBasic/NameConverter.vb#3)]
`NameConverter` implements the <xref:System.Windows.Data.IMultiValueConverter> interface. `NameConverter` takes the values from the individual bindings and stores them in the values object array. The order in which the <xref:System.Windows.Data.Binding> elements appear under the <xref:System.Windows.Data.MultiBinding> element is the order in which those values are stored in the array. The value of the <xref:System.Windows.Data.MultiBinding.ConverterParameter%2A> attribute is referenced by the parameter argument of the <xref:System.Windows.Data.MultiBinding.Converter%2A> method, which performs a switch on the parameter to determine how to format the name.
## See also
- [Convert Bound Data](how-to-convert-bound-data.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,32 @@
---
title: "How to: Set Up Notification of Binding Updates"
ms.date: "03/30/2017"
helpviewer_keywords:
- "notifications [WPF], binding updates"
- "data binding [WPF], notification of binding updates"
- "binding [WPF], updates [WPF], notifications of"
ms.assetid: 5673073e-dbe1-49da-980a-484a88f9595a
---
# How to: Set Up Notification of Binding Updates
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
[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] raises a data update event each time that the binding source or target has been updated. Internally, this event is used to inform the [!INCLUDE[TLA#tla_ui](../../../includes/tlasharptla-ui-md.md)] 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 <xref:System.ComponentModel.INotifyPropertyChanged> interface. For more information, see [Implement Property Change Notification](how-to-implement-property-change-notification.md).
Set the <xref:System.Windows.Data.Binding.NotifyOnTargetUpdated%2A> or <xref:System.Windows.Data.Binding.NotifyOnSourceUpdated%2A> property (or both) to `true` in the binding. The handler you provide to listen for this event must be attached directly to the element where you want to be informed of changes, or to the overall data context if you want to be aware that anything in the context has changed.
Here is an example that shows how to set up for notification when a target property has been updated.
[!code-xaml[DirectionalBinding#2](~/samples/snippets/csharp/VS_Snippets_Wpf/DirectionalBinding/CSharp/Page1.xaml#2)]
You can then assign a handler based on the EventHandler\<T> delegate, *OnTargetUpdated* in this example, to handle the event:
[!code-csharp[DirectionalBinding#3](~/samples/snippets/csharp/VS_Snippets_Wpf/DirectionalBinding/CSharp/Page1.xaml.cs#3)]
[!code-csharp[DirectionalBinding#EndEvent](~/samples/snippets/csharp/VS_Snippets_Wpf/DirectionalBinding/CSharp/Page1.xaml.cs#endevent)]
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](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,41 @@
---
title: "How to: Sort and Group Data Using a View in XAML"
description: Learn how to create a view of a data collection for grouping, sorting, and filtering in the Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
helpviewer_keywords:
- "data binding [WPF], grouping data in views in XAML"
- "XAML [WPF], sorting data in views"
- "grouping data in views in XAML [WPF]"
- "data binding [WPF], sorting data in views in XAML"
- "sorting data in views in XAML [WPF]"
- "XAML [WPF], grouping data in views"
- "views [WPF], sorting data"
- "views [WPF], grouping data"
ms.assetid: 145c8c3f-dbdd-4d0d-816f-90b35eba7eda
---
# How to: Sort and Group Data Using a View in XAML
This example shows how to create a view of a data collection in [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)]. 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.
[!code-xaml[CollectionViewSource#1](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionViewSource/CS/window1.xaml#1)]
The view can then be a binding source, as in the following example:
[!code-xaml[CollectionViewSource#2](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionViewSource/CS/window1.xaml#2)]
For bindings to XML data defined in an <xref:System.Windows.Data.XmlDataProvider> resource, precede the XML name with an @ symbol.
[!code-xaml[CollectionViewSource#XDPChunk](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionViewSource/CS/window1.xaml#xdpchunk)]
[!code-xaml[CollectionViewSource#Attribute](~/samples/snippets/csharp/VS_Snippets_Wpf/CollectionViewSource/CS/window1.xaml#attribute)]
## See also
- <xref:System.Windows.Data.CollectionViewSource>
- [Get the Default View of a Data Collection](how-to-get-the-default-view-of-a-data-collection.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,39 @@
---
title: "How to: Sort Data in a View"
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "data binding [WPF], sorting data in views"
- "data binding [WPF], grouping data in views"
- "grouping data in views [WPF]"
- "views [WPF], sorting data"
- "views [WPF], grouping data"
- "sorting data in views [WPF]"
ms.assetid: f4c43578-01b7-4774-a953-acb95a13b94a
---
# How to: Sort Data in a View
This example describes how to sort data in a view.
## Example
The following example creates a simple <xref:System.Windows.Controls.ListBox> and a <xref:System.Windows.Controls.Button>:
[!code-xaml[ListBoxSort_snip#HowTo](~/samples/snippets/csharp/VS_Snippets_Wpf/ListBoxSort_snip/CSharp/Window1.xaml#howto)]
The <xref:System.Windows.Controls.Primitives.ButtonBase.Click> event handler of the button contains logic to sort the items in the <xref:System.Windows.Controls.ListBox> in the descending order. You can do this because adding items to a <xref:System.Windows.Controls.ListBox> this way adds them to the <xref:System.Windows.Controls.ItemCollection> of the <xref:System.Windows.Controls.ListBox>, and <xref:System.Windows.Controls.ItemCollection> derives from the <xref:System.Windows.Data.CollectionView> class. If you are binding your <xref:System.Windows.Controls.ListBox> to a collection using the <xref:System.Windows.Controls.ItemsControl.ItemsSource%2A> property, you can use the same technique to sort.
[!code-csharp[ListBoxSort_snip#HowToCode](~/samples/snippets/csharp/VS_Snippets_Wpf/ListBoxSort_snip/CSharp/Window1.xaml.cs#howtocode)]
[!code-vb[ListBoxSort_snip#HowToCode](~/samples/snippets/visualbasic/VS_Snippets_Wpf/ListBoxSort_snip/visualbasic/window1.xaml.vb#howtocode)]
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](how-to-get-the-default-view-of-a-data-collection.md). For another example, see [Sort a GridView Column When a Header Is Clicked](../controls/how-to-sort-a-gridview-column-when-a-header-is-clicked.md). For more information about views, see Binding to Collections in [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview).
For an example of how to apply sorting logic in [!INCLUDE[TLA#tla_xaml](../../../includes/tlasharptla-xaml-md.md)], see [Sort and Group Data Using a View in XAML](how-to-sort-and-group-data-using-a-view-in-xaml.md).
## See also
- <xref:System.Windows.Data.ListCollectionView.CustomSort%2A>
- [Sort a GridView Column When a Header Is Clicked](../controls/how-to-sort-a-gridview-column-when-a-header-is-clicked.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [Filter Data in a View](how-to-filter-data-in-a-view.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,48 @@
---
title: "How to: Specify the Binding Source"
description: Learn how to specify the binding source through this example in the Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "binding data [WPF], binding sources"
- "data binding [WPF], binding source"
- "binding sources [WPF]"
ms.assetid: 55d47757-2648-4a52-987f-b767953f168c
---
# How to: Specify the Binding Source
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`.
[!code-xaml[DirectionalBinding#DataContext1](~/samples/snippets/csharp/VS_Snippets_Wpf/DirectionalBinding/CSharp/Page1.xaml#datacontext1)]
[!code-xaml[DirectionalBinding#DataContext2](~/samples/snippets/csharp/VS_Snippets_Wpf/DirectionalBinding/CSharp/Page1.xaml#datacontext2)]
The following example shows the definition of the `NetIncome` class.
[!code-csharp[DirectionalBinding#DataObject](~/samples/snippets/csharp/VS_Snippets_Wpf/DirectionalBinding/CSharp/billsdata.cs#dataobject)]
[!code-vb[DirectionalBinding#DataObject](~/samples/snippets/visualbasic/VS_Snippets_Wpf/DirectionalBinding/VisualBasic/NetIncome.vb#dataobject)]
> [!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](how-to-make-data-available-for-binding-in-xaml.md).
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.
|Property|Description|
|--------------|-----------------|
|<xref:System.Windows.Data.Binding.Source%2A>|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 <xref:System.Windows.Data.Binding.Source%2A> property instead of the `DataContext` property. For more information, see <xref:System.Windows.Data.Binding.Source%2A>.|
|<xref:System.Windows.Data.Binding.RelativeSource%2A>|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 <xref:System.Windows.Data.Binding.RelativeSource%2A>.|
|<xref:System.Windows.Data.Binding.ElementName%2A>|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 <xref:System.Windows.Controls.Slider> to control the height of another control in your application, or if you want to bind the <xref:System.Windows.Controls.ContentControl.Content%2A> of your control to the <xref:System.Windows.Controls.Primitives.Selector.SelectedValue%2A> property of your <xref:System.Windows.Controls.ListBox> control. For more information, see <xref:System.Windows.Data.Binding.ElementName%2A>.|
## See also
- <xref:System.Windows.FrameworkElement.DataContext%2A?displayProperty=nameWithType>
- <xref:System.Windows.FrameworkContentElement.DataContext%2A?displayProperty=nameWithType>
- [Property Value Inheritance](../advanced/property-value-inheritance.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [Binding Declarations Overview](binding-declarations-overview.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,41 @@
---
title: "How to: Specify the Direction of the Binding"
ms.date: "03/30/2017"
helpviewer_keywords:
- "direction of binding [WPF]"
- "binding direction [WPF]"
- "data binding [WPF], direction of binding"
ms.assetid: 37334478-028b-4514-86c9-1420709f4818
---
# How to: Specify the direction of the binding
This example shows how to specify whether the binding updates only the binding target (target) property, the binding source (source) property, or both the target property and the source property.
## Example
You use the <xref:System.Windows.Data.Binding.Mode%2A?displayProperty=nameWithType> property to specify the direction of the binding. The following are the available options for binding updates:
- <xref:System.Windows.Data.BindingMode.TwoWay?displayProperty=nameWithType> updates the target property or the property whenever either the target property or the source property changes.
- <xref:System.Windows.Data.BindingMode.OneWay?displayProperty=nameWithType> updates the target property only when the source property changes.
- <xref:System.Windows.Data.BindingMode.OneTime?displayProperty=nameWithType> updates the target property only when the application starts or when the <xref:System.Windows.FrameworkElement.DataContext%2A> undergoes a change.
- <xref:System.Windows.Data.BindingMode.OneWayToSource?displayProperty=nameWithType> updates the source property when the target property changes.
- <xref:System.Windows.Data.BindingMode.Default?displayProperty=nameWithType> causes the default <xref:System.Windows.Data.Binding.Mode%2A> value of target property to be used.
For more information, see the <xref:System.Windows.Data.BindingMode> enumeration.
The following example shows how to set the <xref:System.Windows.Data.Binding.Mode%2A> property.
[!code-xaml[DirectionalBinding#4](~/samples/snippets/csharp/VS_Snippets_Wpf/DirectionalBinding/CSharp/Page1.xaml#4)]
To detect source changes (applicable to <xref:System.Windows.Data.BindingMode.OneWay> and <xref:System.Windows.Data.BindingMode.TwoWay> bindings), the source must implement a suitable property change notification mechanism such as <xref:System.ComponentModel.INotifyPropertyChanged>. See [Implement Property Change Notification](how-to-implement-property-change-notification.md) for an example of an <xref:System.ComponentModel.INotifyPropertyChanged> implementation.
For <xref:System.Windows.Data.BindingMode.TwoWay> or <xref:System.Windows.Data.BindingMode.OneWayToSource> bindings, you can control the timing of the source updates by setting the <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> property. See <xref:System.Windows.Data.Binding.UpdateSourceTrigger%2A> for more information.
## See also
- <xref:System.Windows.Data.Binding>
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,36 @@
---
title: "How to: Use the Master-Detail Pattern with Hierarchical Data"
ms.date: "03/30/2017"
helpviewer_keywords:
- "data binding [WPF], Master-Detail data paradigm"
- "Master-Detail data paradigm"
ms.assetid: 11429b9e-058d-4084-bfb6-2cf209c8ddf7
---
# How to: Use the Master-Detail Pattern with Hierarchical Data
This example shows how to implement the master-detail scenario.
## 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.
[!code-xaml[MasterDetail#HowTo1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MasterDetail/VisualBasic/Page1.xaml#howto1)]
[!code-xaml[MasterDetail#HowTo2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/MasterDetail/VisualBasic/Page1.xaml#howto2)]
The following is a screenshot of the example. The `Divisions` <xref:System.Windows.Controls.ListBox> automatically tracks selections in the `Leagues` <xref:System.Windows.Controls.ListBox> and display the corresponding data. The `Teams` <xref:System.Windows.Controls.ListBox> tracks selections in the other two <xref:System.Windows.Controls.ListBox> controls.
![Screenshot that shows a Master&#45;detail scenario example.](./media/how-to-use-the-master-detail-pattern-with-hierarchical-data/databinding-master-detail-scenario.png)
The two things to notice in this example are:
1. The three <xref:System.Windows.Controls.ListBox> controls bind to the same source. You set the <xref:System.Windows.Data.Binding.Path%2A> property of the binding to specify which level of data you want the <xref:System.Windows.Controls.ListBox> to display.
2. You must set the <xref:System.Windows.Controls.Primitives.Selector.IsSynchronizedWithCurrentItem%2A> property to `true` on the <xref:System.Windows.Controls.ListBox> controls of which the selection you are tracking. Setting this property ensures that the selected item is always set as the <xref:System.Windows.Controls.ItemCollection.CurrentItem%2A>. Alternatively, if the <xref:System.Windows.Controls.ListBox> gets it data from a <xref:System.Windows.Data.CollectionViewSource>, it synchronizes selection and currency automatically.
The technique is slightly different when you are using XML data. For an example, see [Use the Master-Detail Pattern with Hierarchical XML Data](how-to-use-the-master-detail-pattern-with-hierarchical-xml-data.md).
## See also
- <xref:System.Windows.HierarchicalDataTemplate>
- [Bind to a Collection and Display Information Based on Selection](how-to-bind-to-a-collection-and-display-information-based-on-selection.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [Data Templating Overview](data-templating-overview.md)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,21 @@
---
title: "How to: Use the Master-Detail Pattern with Hierarchical XML Data"
ms.date: "03/30/2017"
helpviewer_keywords:
- "data binding [WPF], Master-Detail data paradigm"
- "Master-Detail data paradigm"
ms.assetid: eb8dbdd8-5871-42bb-a16b-04e655fea677
---
# How to: Use the Master-Detail Pattern with Hierarchical XML Data
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](how-to-use-the-master-detail-pattern-with-hierarchical-data.md). In this example, the data is from the file `League.xml`. Note how the third <xref:System.Windows.Controls.ListBox> control tracks selection changes in the second <xref:System.Windows.Controls.ListBox> by binding to its <xref:System.Windows.Controls.Primitives.Selector.SelectedValue%2A> property.
[!code-xaml[MasterDetailXml#HowTo1](~/samples/snippets/csharp/VS_Snippets_Wpf/MasterDetailXml/CS/Window1.xaml#howto1)]
[!code-xaml[MasterDetailXml#HowTo2](~/samples/snippets/csharp/VS_Snippets_Wpf/MasterDetailXml/CS/Window1.xaml#howto2)]
## See also
- <xref:System.Windows.HierarchicalDataTemplate>
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,30 @@
---
title: "How to: Use XML Namespaces in Data Binding"
ms.date: "03/30/2017"
helpviewer_keywords:
- "XML [WPF], namespaces"
- "data binding [WPF], XML namespaces"
- "namespaces [WPF], XML"
ms.assetid: a47c832f-dc84-48f2-96d5-cde18fc4284b
---
# How to: Use XML Namespaces in Data Binding
## Example
This example shows how to handle namespaces specified in your XML binding source.
If your XML data has the following XML namespace definition:
`<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">`
You can use the <xref:System.Windows.Data.XmlNamespaceMapping> element to map the namespace to a <xref:System.Windows.Data.XmlNamespaceMapping.Prefix%2A>, as in the following example. You can then use the <xref:System.Windows.Data.XmlNamespaceMapping.Prefix%2A> to refer to the XML namespace. The <xref:System.Windows.Controls.ListBox> in this example displays the *title* and *dc:date* of each *item*.
[!code-xaml[XmlnsBindSnippet#XmlNamespaceMapping](~/samples/snippets/csharp/VS_Snippets_Wpf/XmlnsBindSnippet/CS/Window1.xaml#xmlnamespacemapping)]
Note that the <xref:System.Windows.Data.XmlNamespaceMapping.Prefix%2A> 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 <xref:System.Windows.Data.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](how-to-bind-to-xml-data-using-an-xmldataprovider-and-xpath-queries.md)
- [Data Binding Overview](/dotnet/desktop-wpf/data/data-binding-overview)
- [How-to Topics](data-binding-how-to-topics.md)
@@ -0,0 +1,38 @@
---
title: "Data"
ms.date: "03/30/2017"
f1_keywords:
- "AutoGeneratedOrientationPage"
helpviewer_keywords:
- "WPF [WPF], data"
- "Windows Presentation Foundation [WPF], data"
- "data [WPF]"
ms.assetid: dea454e2-abd8-4c53-ba37-d3ed53187d64
---
# Data
[!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] data binding provides a simple and consistent way for applications to present and interact with data. Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML. [!INCLUDE[TLA#tla_winclient](../../../includes/tlasharptla-winclient-md.md)] also provides a mechanism for the transfer of data through drag-and-drop operations.
## In This Section
[Data Binding](/dotnet/desktop-wpf/data/data-binding-overview)
[Drag and Drop](../advanced/drag-and-drop.md)
## Reference
<xref:System.Windows.Data>
<xref:System.Windows.Data.Binding>
<xref:System.Windows.DataTemplate>
<xref:System.Windows.Controls.DataTemplateSelector>
## Related Sections
[Controls](../controls/index.md)
[Styling and Templating](/dotnet/desktop-wpf/fundamentals/styles-templates-overview)
[Data Binding](../advanced/optimizing-performance-data-binding.md)
## See also
- [Walkthrough: My first WPF desktop application](../getting-started/walkthrough-my-first-wpf-desktop-application.md)
- [Walkthrough: Caching Application Data in a WPF Application](../advanced/walkthrough-caching-application-data-in-a-wpf-application.md)
@@ -0,0 +1,130 @@
---
title: L2DBForm.xaml.cs source code
ms.date: 10/22/2019
ms.topic: sample
---
# L2DBForm.xaml.cs source code
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*.
- The namespace variable `myBooks` is initialized to `"http://www.mybooks.com"`.
- The member `bookList` is initialized in the constructor to the CDATA string in *L2DBForm.xaml* with the following line:
```csharp
bookList = (XElement)((ObjectDataProvider)Resources["LoadedBooks"]).Data;
```
## OnAddBook event handler
This method contains the following three statements:
- The first conditional statement is used for input validation.
- The second statement creates a new <xref:System.Xml.Linq.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.
## OnRemove event handler
The `OnRemove` handler is more complicated than the `OnAddBook` handler for two reasons. First, because the raw XML contains preserved white space, matching newlines must also be removed with the book entry. Second, as a convenience, the selection, which was on the deleted item, is reset to the previous one in the list.
However, the core work of removing the selected book item is accomplished by only two statements:
- First, the book element associated with the currently selected item in the list box is retrieved:
```csharp
XElement selBook = (XElement)lbBooks.SelectedItem;
```
- Then, this element is deleted from the data provider:
```csharp
selBook.Remove();
```
Again, dynamic data binding assures that the program's UI is automatically updated.
## Example
### Code
```csharp
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>
public partial class L2XDBForm : System.Windows.Window
{
XNamespace mybooks = "http://www.mybooks.com";
XElement bookList;
public L2XDBForm()
{
InitializeComponent();
bookList = (XElement)((ObjectDataProvider)Resources["LoadedBooks"]).Data;
}
void OnRemoveBook(object sender, EventArgs e)
{
int index = lbBooks.SelectedIndex;
if (index < 0) return;
XElement selBook = (XElement)lbBooks.SelectedItem;
//Get next node before removing element.
XNode nextNode = selBook.NextNode;
selBook.Remove();
//Remove any matching newline node.
if (nextNode != null && nextNode.ToString().Trim().Equals(""))
{ nextNode.Remove(); }
//Set selected item.
if (lbBooks.Items.Count > 0)
{ lbBooks.SelectedItem = lbBooks.Items[index > 0 ? index - 1 : 0]; }
}
void OnAddBook(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tbAddID.Text) ||
String.IsNullOrEmpty(tbAddValue.Text))
{
MessageBox.Show("Please supply both a Book ID and a Value!", "Entry Error!");
return;
}
XElement newBook = new XElement(
mybooks + "book",
new XAttribute("id", tbAddID.Text),
tbAddValue.Text);
bookList.Add(" ", newBook, "\r\n");
}
}
}
```
### Comments
For the associated XAML source for these handlers, see [L2DBForm.xaml source code](l2dbform-xaml-source-code.md).
## See also
- [Walkthrough: LinqToXmlDataBinding example](linq-to-xml-data-binding-sample.md)
- [L2DBForm.xaml source code](l2dbform-xaml-source-code.md)
@@ -0,0 +1,236 @@
---
title: L2DBForm.xaml source code
ms.date: 10/22/2019
ms.topic: sample
---
# L2DBForm.xaml source code
This page contains and describes the XAML source file for the [WPF data binding using LINQ to XML example](linq-to-xml-data-binding-sample.md).
## Overall UI structure
As is typical for a WPF project, this file contains one parent element, a <xref:System.Windows.Window> XML element that's associated with the derived class `L2XDBFrom` in the `LinqToXmlDataBinding` namespace.
The client area is contained within a <xref:System.Windows.Controls.StackPanel> that's given a light blue background. This panel contains four <xref:System.Windows.Controls.DockPanel> UI sections separated by <xref:System.Windows.Controls.Separator> bars. The purpose of these sections is described [here](linq-to-xml-data-binding-sample.md#overview).
Each section contains a label that identifies it. In the first two sections, this label is rotated 90 degrees through the use of a <xref:System.Windows.FrameworkElement.LayoutTransform%2A>. 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 <xref:System.Windows.Controls.StackPanel> is used to align these child controls.
## Window resource section
The opening `<Window.Resources>` tag on line 9 indicates the start of the window resource section. It ends with the closing tag on line 35.
The `<ObjectDataProvider>` tag, which spans lines 11 through 25, declares a <xref:System.Windows.Data.ObjectDataProvider>, named `LoadedBooks`, that uses an <xref:System.Xml.Linq.XElement> as the source. The <xref:System.Xml.Linq.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 <xref:System.Windows.Controls.TextBlock> control, which is used to display the raw XML, has no special XML formatting capabilities.
Lastly, a <xref:System.Windows.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
Text="{Binding Path=Attribute[id].Value}"Text="{Binding Path=Value}"
```
## Data binding code
In addition to the <xref:System.Windows.DataTemplate> element, data binding is used in a number of other places in this file.
In the opening `<StackPanel>` tag on line 38, the <xref:System.Windows.FrameworkElement.DataContext%2A> property of this panel is set to the `LoadedBooks` data provider.
```xaml
DataContext="{Binding Source={StaticResource LoadedBooks}}
```
Setting the data context makes it possible (on line 46) for the <xref:System.Windows.Controls.TextBlock> named `tbRawXml` to display the raw XML by binding to this data provider's `Xml` property:
```xaml
Text="{Binding Path=Xml}"
```
The <xref:System.Windows.Controls.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
ItemTemplate ="{StaticResource BookTemplate}"
```
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 <xref:System.Windows.FrameworkElement.DataContext%2A> of the parent <xref:System.Windows.Controls.StackPanel> to the currently selected item in from the **Book List** UI section (line 82):
```xaml
DataContext="{Binding ElementName=lbBooks, Path=SelectedItem}"
```
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
Text="{Binding Path=Attribute[id].Value}"...Text="{Binding Path=Value}"
```
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
> [!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>
<!-- Template for use in Books List listbox. -->
<DataTemplate x:Key="BookTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="3" Text="{Binding Path=Attribute[id].Value}"/>
<TextBlock Margin="3" Text="-"/>
<TextBlock Margin="3" Text="{Binding Path=Value}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<!-- Main visual content container -->
<StackPanel Background="lightblue" DataContext="{Binding Source={StaticResource LoadedBooks}}">
<!-- Raw XML display section -->
<DockPanel Margin="5">
<Label Background="Gray" FontSize="12" BorderBrush="Black" BorderThickness="1" FontWeight="Bold">XML
<Label.LayoutTransform>
<RotateTransform Angle="90"/>
</Label.LayoutTransform>
</Label>
<TextBlock Name="tbRawXml" Height="200" Background="LightGray" Text="{Binding Path=Xml}" TextTrimming="CharacterEllipsis" />
</DockPanel>
<Separator Height="4" Margin="5" />
<!-- List box to display all books section -->
<DockPanel Margin="5">
<Label Background="Gray" FontSize="12" BorderBrush="Black" BorderThickness="1" FontWeight="Bold">Book List
<Label.LayoutTransform>
<RotateTransform Angle="90"/>
</Label.LayoutTransform>
</Label>
<ListBox Name="lbBooks" Height="200" Width="415" ItemTemplate ="{StaticResource BookTemplate}">
<ListBox.ItemsSource>
<Binding Path="Elements[{http://www.mybooks.com}book]"/>
</ListBox.ItemsSource>
</ListBox>
<Button Margin="5" DockPanel.Dock="Right" Height="30" Width ="130" Content="Remove Selected Book" Click="OnRemoveBook">
<Button.LayoutTransform>
<RotateTransform Angle="90"/>
</Button.LayoutTransform>
</Button>
</DockPanel>
<Separator Height="4" Margin="5" />
<!-- Edit current selection section -->
<DockPanel Margin="5">
<TextBlock Margin="5" Height="30" Width="65" DockPanel.Dock="Right" Background="LightGray" TextWrapping="Wrap" TextAlignment="Center">
Changes are live!
<TextBlock.LayoutTransform>
<RotateTransform Angle="90"/>
</TextBlock.LayoutTransform>
</TextBlock>
<StackPanel>
<Label Width="450" Background="Gray" FontSize="12" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" FontWeight="Bold">Edit Selected Book</Label>
<StackPanel Margin="1" DataContext="{Binding ElementName=lbBooks, Path=SelectedItem}">
<StackPanel Orientation="Horizontal">
<Label Width="40">ID:</Label>
<TextBox Name="editAttributeTextBox" Width="410" Text="{Binding Path=Attribute[id].Value}">
<TextBox.ToolTip>
<TextBlock FontWeight="Bold" TextAlignment="Center">
<Label>Edit the selected book ID and see it changed.</Label>
</TextBlock>
</TextBox.ToolTip>
</TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Width="40">Value:</Label>
<TextBox Name="editValueTextBox" Width="410" Text="{Binding Path=Value}" Height="25">
<TextBox.ToolTip>
<TextBlock FontWeight="Bold" TextAlignment="Center">
<Label>Edit the selected book Value and see it changed.</Label>
</TextBlock>
</TextBox.ToolTip>
</TextBox>
</StackPanel>
</StackPanel>
</StackPanel>
</DockPanel>
<Separator Height="4" Margin="5" />
<!-- Add new book section -->
<DockPanel Margin="5">
<Button Margin="5" Height="30" DockPanel.Dock="Right" Click ="OnAddBook">Add Book
<Button.LayoutTransform>
<RotateTransform Angle="90"/>
</Button.LayoutTransform>
</Button>
<StackPanel>
<Label Width="450" Background="Gray" FontSize="12" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" FontWeight="Bold">Add New Book</Label>
<StackPanel Margin="1">
<StackPanel Orientation="Horizontal">
<Label Width="40">ID:</Label>
<TextBox Name="tbAddID" Width="410">
<TextBox.ToolTip>
<TextBlock FontWeight="Bold" TextAlignment="Center">
<Label>Enter a book ID and Value pair, then click Add Book.</Label>
</TextBlock>
</TextBox.ToolTip>
</TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Width="40">Value:</Label>
<TextBox Name="tbAddValue" Width="410" Height="25">
<TextBox.ToolTip>
<TextBlock FontWeight="UltraBold" TextAlignment="Center">
<Label>Enter a book ID and Value pair, then click Add Book.</Label>
</TextBlock>
</TextBox.ToolTip>
</TextBox>
</StackPanel>
</StackPanel>
</StackPanel>
</DockPanel>
</StackPanel>
</Window>
```
### Comments
For the C# source code for the event handlers associated with the WPF UI elements, see [L2DBForm.xaml.cs source code](l2dbform-xaml-cs-source-code.md).
## See also
- [Walkthrough: LinqToXmlDataBinding example](linq-to-xml-data-binding-sample.md)
- [L2DBForm.xaml.cs source code](l2dbform-xaml-cs-source-code.md)
@@ -0,0 +1,89 @@
---
title: LINQ to XML data binding example
ms.date: 10/22/2019
ms.topic: sample
helpviewer_keywords:
- linq to xml data binding sample
---
# LINQ to XML data binding sample
This article describes the LinqToXmlDataBinding sample, a Windows Presentation Foundation (WPF) app that binds user interface components to an embedded XML data source.
## 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.
There are two primary source files:
- [L2DBForm.xaml](l2dbform-xaml-source-code.md) 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.
- [L2DBForm.xaml.cs](l2dbform-xaml-cs-source-code.md) contains the initialization and event-handling methods associated with the UI.
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.
## Run the sample
This section shows how to create and build the LinqToXmlDataBinding project in Visual Studio, and how to run the resulting LinqToXmlDataBinding Windows Presentation Foundation (WPF) app.
### Create the project
1. Open Visual Studio and create a C# **WPF App** named **LinqToXmlDataBinding**.
The project should target the .NET Framework 3.5 (or later).
1. If not already present, add project references for the following .NET assemblies:
- System.Data
- System.Data.DataSetExtensions
- System.Xml
- System.Xml
1. Build the solution by pressing **Ctrl**+**Shift**+**B**, then run it by pressing **F5**.
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**.
The dependent source file Window1.xaml.cs is automatically renamed to L2XDBForm.xaml.cs.
1. Replace the source code found in the file **L2XDBForm.xaml** with the [L2DBForm.xaml source code](l2dbform-xaml-source-code.md). Use the XAML source view to work with this file.
1. Similarly, replace the source in **L2XDBForm.xaml.cs** with the [L2DBForm.xaml.cs source code](l2dbform-xaml-cs-source-code.md).
1. In the file **App.xaml**, replace all occurrences of the string **Window1.xaml** with **L2XDBForm.xaml**.
1. Build the solution by pressing **Ctrl**+**Shift**+**B**.
### Run the app
The LinqToXmlDataBinding app enables the user to view and manipulate a list of books that's stored as an embedded XML element. Run the app by pressing **F5** (Start Debugging) or **Ctrl**+**F5** (Start Without Debugging).
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 <xref:System.Windows.Controls.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 <xref:System.Windows.Controls.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** <xref:System.Windows.Controls.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.
### Edit a book entry
1. Select the book entry in the second **Book List** section.
Its current values are displayed in the **Edit Selected Book** section.
1. Edit the values using the keyboard. As soon as either <xref:System.Windows.Controls.TextBox> control loses focus, changes are automatically propagated to the XML source and book listings.
@@ -0,0 +1,30 @@
---
title: LINQ to XML dynamic properties reference
ms.date: 10/22/2019
ms.topic: reference
---
# LINQ to XML dynamic properties
This section provides reference information about the dynamic properties in LINQ to XML. Specifically, these properties are exposed by the <xref:System.Xml.Linq.XAttribute> and <xref:System.Xml.Linq.XElement> classes, which are in the <xref:System.Xml.Linq> namespace.
As explained in the topic [Overview of WPF data binding with LINQ to XML](wpf-data-binding-with-linq-to-xml-overview.md), 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 <xref:System.Xml.Linq.XAttribute> and <xref:System.Xml.Linq.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 <xref:System.Xml.Linq.XAttribute> and <xref:System.Xml.Linq.XElement> classes, that resolve to a single value.
- Indexed values, such as the [Elements](elements-xelement-dynamic-property.md) and [Descendants](descendants-xelement-dynamic-property.md) properties of <xref:System.Xml.Linq.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 <xref:System.Collections.Generic.IEnumerable%601> use deferred execution. For more information about deferred execution, see [Introduction to LINQ queries (C#)](/dotnet/csharp/programming-guide/concepts/linq/introduction-to-linq-queries).
## Reference
- <xref:System.Xml.Linq>
- <xref:System.Xml.Linq.XElement?displayProperty=fullName>
- <xref:System.Xml.Linq.XAttribute?displayProperty=fullName>
## See also
- [WPF data binding with LINQ to XML](wpf-data-binding-with-linq-to-xml-overview.md)
- [WPF data binding with LINQ to XML overview](wpf-data-binding-with-linq-to-xml-overview.md)
- [Introduction to LINQ queries (C#)](/dotnet/csharp/programming-guide/concepts/linq/introduction-to-linq-queries)
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

@@ -0,0 +1,117 @@
- name: Data binding documentation
href: index.md
- name: Overview
href: /dotnet/desktop-wpf/data/data-binding-overview?toc=/dotnet/framework/wpf/data/toc.json&bc=/dotnet/framework/wpf/data/breadcrumb/toc.json
- name: Binding sources
href: binding-sources-overview.md
- name: Data templating
href: data-templating-overview.md
- name: Binding declarations
href: binding-declarations-overview.md
- name: How-to
items:
- name: How-to topics for data binding
href: data-binding-how-to-topics.md
- name: Create a simple binding
href: how-to-create-a-simple-binding.md
- name: Specify the binding source
href: how-to-specify-the-binding-source.md
- name: Make data available for binding in XAML
href: how-to-make-data-available-for-binding-in-xaml.md
- name: Control when the TextBox text updates the source
href: how-to-control-when-the-textbox-text-updates-the-source.md
- name: Specify the direction of the binding
href: how-to-specify-the-direction-of-the-binding.md
- name: Bind to a collection and display information based on selection
href: how-to-bind-to-a-collection-and-display-information-based-on-selection.md
- name: Bind to an enumeration
href: how-to-bind-to-an-enumeration.md
- name: Bind the properties of two controls
href: how-to-bind-the-properties-of-two-controls.md
- name: Implement binding validation
href: how-to-implement-binding-validation.md
- name: Implement validation logic on custom objects
href: how-to-implement-validation-logic-on-custom-objects.md
- name: Get the binding object from a bound target property
href: how-to-get-the-binding-object-from-a-bound-target-property.md
- name: Implement a CompositeCollection
href: how-to-implement-a-compositecollection.md
- name: Convert bound data
href: how-to-convert-bound-data.md
- name: Create a binding in code
href: how-to-create-a-binding-in-code.md
- name: Get the default view of a data collection
href: how-to-get-the-default-view-of-a-data-collection.md
- name: Navigate through the objects in a data CollectionView
href: how-to-navigate-through-the-objects-in-a-data-collectionview.md
- name: Filter data in a view
href: how-to-filter-data-in-a-view.md
- name: Sort data in a view
href: how-to-sort-data-in-a-view.md
- name: Sort and group data using a view in XAML
href: how-to-sort-and-group-data-using-a-view-in-xaml.md
- name: Use the master-detail pattern with hierarchical data
href: how-to-use-the-master-detail-pattern-with-hierarchical-data.md
- name: Use the master-detail pattern with hierarchical XML data
href: how-to-use-the-master-detail-pattern-with-hierarchical-xml-data.md
- name: Produce a value based on a list of bound Items
href: how-to-produce-a-value-based-on-a-list-of-bound-items.md
- name: Implement property change notification
href: how-to-implement-property-change-notification.md
- name: Create and bind to an ObservableCollection
href: how-to-create-and-bind-to-an-observablecollection.md
- name: Implement PriorityBinding
href: how-to-implement-prioritybinding.md
- name: Bind to XML data using an XMLDataProvider and XPath queries
href: how-to-bind-to-xml-data-using-an-xmldataprovider-and-xpath-queries.md
- name: Bind to query results
href: how-to-bind-to-xdocument-xelement-or-linq-for-xml-query-results.md
- name: Bind to the results of a LINQ Query
href: how-to-bind-to-the-results-of-a-linq-query.md
- name: Use XML namespaces in data binding
href: how-to-use-xml-namespaces-in-data-binding.md
- name: Bind to an ADO.NET data source
href: how-to-bind-to-an-ado-net-data-source.md
- name: Bind to a method
href: how-to-bind-to-a-method.md
- name: Set up notification of binding updates
href: how-to-set-up-notification-of-binding-updates.md
- name: Clear bindings
href: how-to-clear-bindings.md
- name: Find DataTemplate-generated elements
href: how-to-find-datatemplate-generated-elements.md
- name: Data binding with LINQ to XML
items:
- name: Overview
href: wpf-data-binding-with-linq-to-xml-overview.md
- name: LINQ to XML dynamic properties
items:
- name: Overview
displayName: LINQ to XML dynamic properties
href: linq-to-xml-dynamic-properties.md
- name: XAttribute dynamic properties
items:
- name: Value
href: value-xattribute-dynamic-property.md
- name: XElement dynamic properties
items:
- name: Attribute
href: attribute-xelement-dynamic-property.md
- name: Element
href: element-xelement-dynamic-property.md
- name: Elements
href: elements-xelement-dynamic-property.md
- name: Descendants
href: descendants-xelement-dynamic-property.md
- name: Value
href: value-xelement-dynamic-property.md
- name: Xml
href: xml-xelement-dynamic-property.md
- name: Sample
items:
- name: LINQ to XML data binding sample
href: linq-to-xml-data-binding-sample.md
- name: L2DBForm.xaml source code
href: l2dbform-xaml-source-code.md
- name: L2DBForm.xaml.cs source code
href: l2dbform-xaml-cs-source-code.md
@@ -0,0 +1,37 @@
---
title: Value (XAttribute dynamic property)
ms.date: 10/22/2019
ms.topic: reference
apiname:
- "XAttribute.Value"
apitype: "Assembly"
---
# Value (XAttribute dynamic property)
Gets or sets the value of the XML attribute.
## Syntax
```xaml
attrib.Value
```
## Property value/return value
A <xref:System.String> containing the value of this attribute.
## Exceptions
|Exception type|Condition|
| - |---------------|
|<xref:System.ArgumentNullException>|When setting, the `value` is `null`.|
## Remarks
This property is equivalent to the <xref:System.Xml.Linq.XAttribute.Value%2A> property of the <xref:System.Xml.Linq.XAttribute?displayProperty=fullName> class, but this dynamic property also supports change notifications.
## See also
- <xref:System.Xml.Linq.XAttribute.Value%2A?displayProperty=fullName>
- [XAttribute class dynamic properties](value-xattribute-dynamic-property.md)
- [Attribute](attribute-xelement-dynamic-property.md)
@@ -0,0 +1,28 @@
---
title: Value (XElement dynamic property)
ms.date: 10/22/2019
ms.topic: reference
---
# Value (XElement dynamic property)
Gets or sets the content of the element.
## Syntax
```xaml
elem.Value
```
## Property value/return value
A <xref:System.String> that represents the concatenated contents of the element.
## Remarks
This property is equivalent to the <xref:System.Xml.Linq.XElement.Value%2A> property of the <xref:System.Xml.Linq.XElement?displayProperty=fullName> class, but this dynamic property also supports change notifications.
## See also
- <xref:System.Xml.Linq.XElement.Value%2A?displayProperty=fullName>
- [XElement class dynamic properties](attribute-xelement-dynamic-property.md)
- [Xml](xml-xelement-dynamic-property.md)
@@ -0,0 +1,88 @@
---
title: Data binding with LINQ to XML
ms.date: 10/22/2019
ms.topic: conceptual
---
# Overview of WPF data binding with LINQ to XML
This article introduces the dynamic data binding features in the <xref: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 <xref:System.Xml.Linq.XAttribute?displayProperty=fullName> and <xref:System.Xml.Linq.XElement?displayProperty=fullName>.
## XAML and LINQ to XML
The Extensible Application Markup Language (XAML) is an XML dialect created by Microsoft to support .NET technologies. It is used in WPF to represent user interface elements and related features, such as events and data binding. In Windows Workflow Foundation, XAML is used to represent program structure, such as program control (*workflows*). XAML enables the declarative aspects of a technology to be separated from the related procedural code that defines the more individualized behavior of a program.
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.
This documentation describes the second scenario.
## Data binding in the Windows Presentation Foundation
WPF data binding enables a UI element to associate one of its properties with a data source. A simple example of this is a <xref:System.Windows.Controls.Label> whose text presents the value of a public property in a user-defined object. WPF data binding relies on the following components:
|Component|Description|
|---------------|-----------------|
|Binding target|The UI element to be associated with the data source. Visual elements in WPF are derived from the <xref:System.Windows.UIElement> class.|
|Target property|The *dependency property* of the binding target that reflects the value of the data-binding source. Dependency properties are directly supported by the <xref:System.Windows.DependencyObject> class, which <xref:System.Windows.UIElement> derives from.|
|Binding source|The source object for one or more values that are supplied to the UI element for 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 <xref:System.Windows.DependencyObject>.|
|Source path|The property of the binding source that resolves to the value or set of values that is to be bound.|
A dependency property is a concept specific to WPF that represent a dynamically computed property of a UI element. For example, dependency properties often have default values or values that are provided by a parent element. These special properties are backed by instances of the <xref:System.Windows.DependencyProperty> class (and not fields as with standard properties). For more information, see [Dependency Properties Overview](../advanced/dependency-properties-overview.md).
### Dynamic data binding in WPF
By default, data binding occurs only when the target UI element is initialized. This is called *one-time* binding. For most purposes, this is insufficient; typically, a data-binding solution requires that the changes be dynamically propagated at run time using one of the following:
- *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 <xref:System.ComponentModel.INotifyPropertyChanged> interface or by using a *PropertyNameChanged* pattern for each property supported.
For more information about data binding in WPF, see [Data Binding (WPF)](/dotnet/framework/wpf/data/data-binding-wpf).
## Dynamic properties in LINQ to XML classes
Most LINQ to XML classes do not qualify as proper WPF dynamic data sources. Some of the most useful information is available only through methods, not properties, and properties in these classes do not implement change notifications. To support WPF data binding, LINQ to XML exposes a set of *dynamic properties*.
These dynamic properties are special run-time properties that duplicate the functionality of existing methods and properties in the <xref:System.Xml.Linq.XAttribute> and <xref:System.Xml.Linq.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](linq-to-xml-dynamic-properties.md).
> [!NOTE]
> Many of the standard public properties, found in the various classes in the <xref: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.
### Access dynamic properties
The dynamic properties in the <xref:System.Xml.Linq.XAttribute> and <xref:System.Xml.Linq.XElement> classes cannot be accessed like standard properties. For example, in CLR-compliant languages such as C#, they cannot be:
- 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 <xref:System.ComponentModel> namespace.
In contrast, however, in an XML source dynamic properties can be accessed through a straightforward notation in the following form:
```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>]
```
For more information, see [LINQ to XML Dynamic Properties](linq-to-xml-dynamic-properties.md).
To implement WPF dynamic binding, dynamic properties will be used with facilities provided by the <xref:System.Windows.Data> namespace, most notably the <xref:System.Windows.Data.Binding> class.
## See also
- [WPF Data Binding with LINQ to XML](wpf-data-binding-with-linq-to-xml-overview.md)
- [LINQ to XML Dynamic Properties](linq-to-xml-dynamic-properties.md)
- [XAML in WPF](../advanced/xaml-in-wpf.md)
- [Data Binding (WPF)](/dotnet/framework/wpf/data/data-binding-wpf)
- [Using Workflow Markup](https://docs.microsoft.com/previous-versions/dotnet/netframework-3.5/ms735921(v=vs.90))
@@ -0,0 +1,29 @@
---
title: Xml (XElement dynamic property)
ms.date: 10/22/2019
ms.topic: reference
apiname:
- "XElement.Xml"
---
# Xml (XElement dynamic property)
Gets the unformatted XML content of the element.
## Syntax
```xaml
elem.Xml
```
## Property value/return value
A <xref:System.String> that represents the unformatted XML content of the element.
## Remarks
This property is equivalent to the <xref:System.Xml.Linq.XNode.ToString(System.Xml.Linq.SaveOptions)> method of the <xref:System.Xml.Linq.XNode?displayProperty=fullName> class, with the `SaveOptions` parameter set to <xref:System.Xml.Linq.SaveOptions>.
## See also
- [XElement class dynamic properties](attribute-xelement-dynamic-property.md)
- [Value](value-xelement-dynamic-property.md)