Binding Class
Definition
Provides high-level access to the definition of a binding, which connects the properties of binding target objects (typically, WPF elements), and any data source (for example, a database, an XML file, or any object that contains data).
Remarks
Windows Presentation Foundation (WPF) data binding provides a simple and consistent way for applications to present and interact with data. Data binding enables you to synchronize the values of the properties of two different objects.
To establish a binding, use the Binding class or one of the other classes that inherit BindingBase. Regardless of what object you are binding and the nature of your data source, each binding follows the model illustrated by the following figure.
The figure demonstrates the following fundamental WPF data binding concepts.
Each binding typically has these four components: a binding target object, a target property, a binding source, and a Path to the value in the binding source to use. For example, if you want to bind the content of a TextBox to the Name property of an Employee object, your target object is the TextBox, the target property is the Text property, the value to use is Name, and the source object is the Employee object.
The target property must be a dependency property. This also means that you cannot bind a field. Most properties of UIElement objects are dependency properties and most dependency properties, except read-only ones, support data binding by default. (Only DependencyObject types can define dependency properties and all UIElement objects derive from DependencyObject.)
Although not specified in the figure, it should be noted that the binding source object is not restricted to being a custom CLR object. WPF data binding supports data in the form of CLR objects and XML. To provide some examples, your binding source may be a UIElement, any list object, a CLR object that is associated with ADO.NET data or Web Services, or an XmlNode that contains your XML data.
Use the Mode property to specify the direction of the data flow. To detect source changes in one-way or two-way bindings, the source must implement a suitable property change notification mechanism such as INotifyPropertyChanged. For an example, see How to: Implement Property Change Notification. The UpdateSourceTrigger property specifies the timing of source updates. For more information, see «Basic Data Binding Concepts» in Data Binding Overview.
XAML Attribute Usage
XAML Values
declaration
Zero or more attribute-assignment clauses separated by commas (,). For more information, see Binding Markup Extension or Binding Declarations Overview.
Constructors
Initializes a new instance of the Binding class.
Initializes a new instance of the Binding class with an initial path.
Fields
Used as a returned value to instruct the binding engine not to perform any action.
Used as the PropertyName of PropertyChangedEventArgs to indicate that an indexer property has changed.
Identifies the SourceUpdated attached event.
Identifies the TargetUpdated attached event.
Identifies the XmlNamespaceManager attached property.
Properties
Gets or sets opaque data passed to the asynchronous data dispatcher.
Gets or sets the name of the BindingGroup to which this binding belongs.
(Inherited from BindingBase)
Gets or sets a value that indicates whether to evaluate the Path relative to the data item or the DataSourceProvider object.
Gets or sets the converter to use.
Gets or sets the culture in which to evaluate the converter.
Gets or sets the parameter to pass to the Converter.
Gets or sets the amount of time, in milliseconds, to wait before updating the binding source after the value on the target changes.
(Inherited from BindingBase)
Gets or sets the name of the element to use as the binding source object.
Gets or sets the value to use when the binding is unable to return a value.
(Inherited from BindingBase)
Gets or sets a value that indicates whether the Binding should get and set values asynchronously.
Gets or sets a value that indicates the direction of the data flow in the binding.
Gets or sets a value that indicates whether to raise the SourceUpdated event when a value is transferred from the binding target to the binding source.
Gets or sets a value that indicates whether to raise the TargetUpdated event when a value is transferred from the binding source to the binding target.
Gets or sets a value that indicates whether to raise the Error attached event on the bound object.
Gets or sets the path to the binding source property.
Gets or sets the binding source by specifying its location relative to the position of the binding target.
Gets or sets the object to use as the binding source.
Gets or sets a string that specifies how to format the binding if it displays the bound value as a string.
(Inherited from BindingBase)
Gets or sets the value that is used in the target when the value of the source is null .
(Inherited from BindingBase)
Gets or sets a handler you can use to provide custom logic for handling exceptions that the binding engine encounters during the update of the binding source value. This is only applicable if you have associated an ExceptionValidationRule with your binding.
Gets or sets a value that determines the timing of binding source updates.
Gets or sets a value that indicates whether to include the DataErrorValidationRule.
Gets or sets a value that indicates whether to include the ExceptionValidationRule.
Gets or sets a value that indicates whether to include the NotifyDataErrorValidationRule.
Gets a collection of rules that check the validity of the user input.
Gets or sets an XPath query that returns the value on the XML binding source to use.
Attached Properties
Gets or sets the XmlNamespaceManager used to perform namespace-aware XPath queries in XML bindings.
Methods
Adds a handler for the SourceUpdated attached event.
Adds a handler for the TargetUpdated attached event.
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Serves as the default hash function.
(Inherited from Object)
Gets the Type of the current instance.
(Inherited from Object)
Returns an XML namespace manager object used by the binding attached to the specified object.
Creates a shallow copy of the current Object.
(Inherited from Object)
Returns an object that should be set on the property where this binding and extension are applied.
(Inherited from BindingBase)
Removes a handler for the SourceUpdated attached event.
Removes a handler for the TargetUpdated attached event.
Sets a namespace manager object used by the binding attached to the provided element.
Returns a value that indicates whether serialization processes should serialize the effective value of the FallbackValue property on instances of this class.
(Inherited from BindingBase)
Indicates whether the Path property should be persisted.
Indicates whether the Source property should be persisted.
Returns a value that indicates whether the TargetNullValue property should be serialized.
(Inherited from BindingBase)
Indicates whether the ValidationRules property should be persisted.
Returns a string that represents the current object.
(Inherited from Object)
Attached Events
Occurs when a value is transferred from the binding target to the binding source, but only for bindings with the NotifyOnSourceUpdated value set to true .
Occurs when a value is transferred from the binding source to the binding target, but only for bindings with the NotifyOnTargetUpdated value set to true .
System. Windows. Data Пространство имен
Классы, используемые для привязки свойств к источникам данных, классы поставщиков источников данных и зависящие от данных реализации коллекций и представлений. Contains classes used for binding properties to data sources, data source provider classes, and data-specific implementations of collections and views.
Классы
Предоставляет высокоуровневый доступ к определению привязки, соединяющей свойства целевых объектов привязки (как правило, элементов WPF) и любой источник данных (например, базу данных, XML-файл или любой объект, который содержит данные). Provides high-level access to the definition of a binding, which connects the properties of binding target objects (typically, WPF elements), and any data source (for example, a database, an XML file, or any object that contains data).
Определяет общие характеристики классов Binding, PriorityBindingи MultiBinding. Defines the common characteristics of the Binding, PriorityBinding, and MultiBinding classes.
Содержит сведения об одном экземпляре Binding. Contains information about a single instance of a Binding.
Содержит коллекцию привязок и объекты ValidationRule, используемые для проверки объекта. Contains a collection of bindings and ValidationRule objects that are used to validate an object.
Представляет CollectionView для коллекций, которые реализуют интерфейс IBindingList, например представления данных объектов данных ActiveX (ADO). Represents the CollectionView for collections that implement IBindingList, such as Microsoft ActiveX Data Objects (ADO) data views.
Предоставляет статические методы для работы с привязками, включая объекты Binding, MultiBinding и PriorityBinding. Provides static methods to manipulate bindings, including Binding, MultiBinding, and PriorityBinding objects.
Хранит существующую структуру коллекции, например ObservableCollection или DataSet, для использования внутри CompositeCollection. Holds an existing collection structure, such as an ObservableCollection or a DataSet, to be used inside a CompositeCollection.
Предоставляет данные для события CollectionRegistering. Provides data for the CollectionRegistering event.
Представляет представление для группирования, сортировки, фильтрации коллекции данных и перемещения по ней. Represents a view for grouping, sorting, filtering, and navigating a data collection.
Представляет группу, созданную объектом CollectionView на основе GroupDescriptions. Represents a group created by a CollectionView object based on the GroupDescriptions.
Предоставляет данные для события CollectionViewRegistering. Provides data for the CollectionViewRegistering event.
Прокси языка XAML класса CollectionView. The Extensible Application Markup Language (XAML) proxy of a CollectionView class.
Позволяет отображать несколько коллекций и элементов в виде одного списка. Enables multiple collections and items to be displayed as a single list.
Предоставляет реализацию WeakEventManager таким образом, что пользователь может использовать шаблон «слабого прослушивателя событий» для присоединения прослушивателей для события DataChanged. Provides a WeakEventManager implementation so that you can use the «weak event listener» pattern to attach listeners for the DataChanged event.
Общий базовый класс и контракт для объектов DataSourceProvider, являющихся фабриками, выполняющими некоторые запросы для получения отдельного объекта или списка объектов, которые можно использовать в качестве объектов источника привязки. Common base class and contract for DataSourceProvider objects, which are factories that execute some queries to produce a single object or a list of objects that you can use as binding source objects.
Инкапсулирует аргументы для событий передачи данных. Encapsulates arguments for data transfer events.
Предоставляет сведения и данные о событии, связанных с событием Filter. Provides information and event data that is associated with the Filter event.
Обозначает представление коллекции для коллекций, которые реализуют IList. Represents the collection view for collections that implement IList.
Описывает коллекцию объектов Binding, присоединенных к одному целевому свойству привязки. Describes a collection of Binding objects attached to a single binding target property.
Содержит сведения об одном экземпляре MultiBinding. Contains instance information about a single instance of a MultiBinding.
Заключает в оболочку и создает объект, который можно использовать в качестве источника привязки. Wraps and creates an object that you can use as a binding source.
Описывает коллекцию объектов Binding, присоединенную к одному свойству целевого объекта привязки, получающему значение из первой привязки в коллекции, которая успешно создает значение. Describes a collection of Binding objects that is attached to a single binding target property, which receives its value from the first binding in the collection that produces a value successfully.
Содержит сведения об одном экземпляре PriorityBinding. Contains instance information about a single instance of a PriorityBinding.
Описывает группирование элементов, используя имя свойства в качестве критерия. Describes the grouping of items using a property name as the criteria.
Реализует расширение разметки, которое описывает расположение источника привязки относительно положения целевого объекта привязки. Implements a markup extension that describes the location of the binding source relative to the position of the binding target.
Представляет атрибут, который позволяет автору преобразователя значений указывать типы данных, участвующие в реализации преобразователя. Represents an attribute that allows the author of a value converter to specify the data types involved in the implementation of the converter.
Исключение, генерируемое методом GetValue(Object, String), когда значение недоступно. The exception that is thrown by the GetValue(Object, String) method when the value is not available.
Предоставляет декларативный доступ к данным XML для привязки данных. Enables declarative access to XML data for data binding.
Объявляет сопоставление между универсальным кодом ресурса (URI) и префиксом. Declares a mapping between a uniform resource identifier (URI) and a prefix.
Представляет коллекцию объектов XmlNamespaceMapping. Represents a collection of XmlNamespaceMapping objects.
Интерфейсы
Позволяет применять пользовательскую логику в MultiBinding. Provides a way to apply custom logic in a MultiBinding.
Позволяет применять пользовательскую логику к привязке. Provides a way to apply custom logic to a binding.
Перечисления
Описывает направление потока данных в привязке. Describes the direction of the data flow in a binding.
Описывает состояние привязки. Describes the status of a binding.
Описывает расположение источника привязки относительно положения целевого объекта привязки. Describes the location of the binding source relative to the position of the binding target.
Описывает расписание обновлений источника привязки. Describes the timing of binding source updates.
Делегаты
Представьте метод, который будет синхронизировать коллекцию для доступа между потоками. Represent the method that synchronizes a collection for cross-thread access.
Представляет метод обработки события Filter. Represents the method that will handle the Filter event.
Представление метода, используемого для обеспечения настраиваемой логики для выбора GroupDescription на основе родительской группы и ее уровня. Represents a method that is used to provide custom logic to select the GroupDescription based on the parent group and its level.
Представляет метод, который обрабатывает исключения, вызываемые во время обновления значения источника привязки. Represents the method that handles exceptions that are thrown during the update of the binding source value. Он должен использоваться с ExceptionValidationRule. This must be used with the ExceptionValidationRule.