BindingGroup 类


包含绑定集合和用于验证对象的 ValidationRule 对象。Contains a collection of bindings and ValidationRule objects that are used to validate an object.

public ref class BindingGroup : System::Windows::DependencyObject
public class BindingGroup : System.Windows.DependencyObject
type BindingGroup = class
    inherit DependencyObject
Public Class BindingGroup
Inherits DependencyObject


下面的示例创建一个应用程序,该应用程序提示用户输入商品的描述和价格以及产品/服务的到期日期。The following examples create an application that prompts the user to enter the description and price of an item and the date that the offer expires. 应用程序将在窗体下显示项的当前信息。The application displays the current information for the item below the form. 用户可以提交或取消更改。The user can submit or cancel the changes.

应用程序执行以下操作来实现此行为。The application does the following to achieve this behavior.

下面的示例创建 (UI) 应用程序的用户界面。The following example creates the user interface (UI) of the application. StackPanel 具有一个 BindingGroup ,它包含用于 ValidationRule 验证项的,如前文所述。The root StackPanel has a BindingGroup that contains a ValidationRule that validates the item, as described previously. 属性和属性的绑定对象将 Price OfferExpires 成为的一部分 BindingGroup ,并且每个绑定都有一个 ValidationRule 来确保价格和日期分别是有效值。The binding objects on the Price property and the OfferExpires property become part of the BindingGroup and each binding has a ValidationRule to make sure that price and date, respectively, are valid values. 单个属性的验证规则将在 ValidationRule 上的中运行 BindingGroupThe validation rules for the individual properties run before the ValidationRule on the BindingGroup.

<StackPanel Name="stackPanel1"  Margin="10" Width="250"

    <Style TargetType="HeaderedContentControl">
      <Setter Property="Margin" Value="2"/>
      <Setter Property="Focusable" Value="False"/>
      <Setter Property="Template">
          <ControlTemplate TargetType="HeaderedContentControl">
            <DockPanel LastChildFill="False">
              <ContentPresenter ContentSource="Header" DockPanel.Dock="Left" Focusable="False" VerticalAlignment="Center"/>
              <ContentPresenter ContentSource="Content" Margin="5,0,0,0" DockPanel.Dock="Right" VerticalAlignment="Center"/>


    <Style TargetType="Button">
      <Setter Property="Width" Value="100"/>
      <Setter Property="Margin" Value="10,15,15,15"/>


    <BindingGroup NotifyOnValidationError="True">
        <src:ValidateDateAndPrice ValidationStep="ConvertedProposedValue" />
  <TextBlock FontSize="14" Text="Enter an item for sale"/>
  <HeaderedContentControl Header="Description">
    <TextBox Width="150" Text="{Binding Path=Description, Mode=TwoWay}"/>
  <HeaderedContentControl Header="Price">
    <TextBox Name="priceField"  Width="150">
        <Binding Path="Price" Mode="TwoWay" >
  <HeaderedContentControl Header="Date Offer Ends">
    <TextBox Name="dateField" Width="150" >
        <Binding Path="OfferExpires" StringFormat="d" >
  <StackPanel Orientation="Horizontal">
    <Button IsDefault="True" Click="Submit_Click">_Submit</Button>
    <Button IsCancel="True" Click="Cancel_Click">_Cancel</Button>
  <HeaderedContentControl Header="Description">
    <TextBlock Width="150" Text="{Binding Path=Description}"/>
  <HeaderedContentControl Header="Price">
    <TextBlock Width="150" Text="{Binding Path=Price, StringFormat=c}"/>
  <HeaderedContentControl Header="Date Offer Ends">
    <TextBlock Width="150" Text="{Binding Path=OfferExpires, StringFormat=d}"/>

下面的示例演示应用程序的事件处理程序。The following example shows the event handlers for the application. 当用户单击 "提交" 按钮时,应用程序会调用 CommitEdit 以运行 ValidationRule 与相关联的每个 BindingGroupWhen the user clicks the Submit button, the application calls CommitEdit to run each ValidationRule that is associated with the BindingGroup. 如果每个成功,则会将 ValidationRule CommitEdit 值保存到对象并结束编辑事务。If each ValidationRule succeeds, CommitEdit saves the values to the object and ends the edit transaction. 如果 CommitEdit 成功,则应用程序将开始另一个编辑事务。If CommitEdit is successful, the application begins another edit transaction. ValidationRule 失败时,将 Validation.Error 发生事件,因为应用程序 NotifyOnValidationErrortrue 前面的 BindingGroup 示例中的 (上) 。When a ValidationRule fails, the Validation.Error event occurs because the application set NotifyOnValidationError to true on the BindingGroup (in the previous example). ItemError 处理 Validation.Error 事件,并向用户显示有关验证错误的信息。ItemError handles the Validation.Error event and displays information about the validation error to the user. 该示例还处理的 Loaded 事件和 " StackPanel 取消" Click 按钮的事件 。The example also handles the Loaded event for the StackPanel and the Click event for the Cancel button.

private void Submit_Click(object sender, RoutedEventArgs e)
    if (stackPanel1.BindingGroup.CommitEdit())
        MessageBox.Show("Item submitted");

// This event occurs when a ValidationRule in the BindingGroup
// or in a Binding fails.
private void ItemError(object sender, ValidationErrorEventArgs e)
    if (e.Action == ValidationErrorEventAction.Added)

void stackPanel1_Loaded(object sender, RoutedEventArgs e)
    // Set the DataContext to a PurchaseItem object.
    // The BindingGroup and Binding objects use this as
    // the source.
    stackPanel1.DataContext = new PurchaseItem();

    // Begin an edit transaction that enables
    // the object to accept or roll back changes.

private void Cancel_Click(object sender, RoutedEventArgs e)
    // Cancel the pending changes and begin a new edit transaction.

Private Sub Submit_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If stackPanel1.BindingGroup.CommitEdit() Then
        MessageBox.Show("Item submitted")
    End If

End Sub

' This event occurs when a ValidationRule in the BindingGroup
' or in a Binding fails.
Private Sub ItemError(ByVal sender As Object, ByVal e As ValidationErrorEventArgs)
    If e.Action = ValidationErrorEventAction.Added Then

    End If
End Sub

Private Sub stackPanel1_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
    ' Set the DataContext to a PurchaseItem object.
    ' The BindingGroup and Binding objects use this as
    ' the source.
    stackPanel1.DataContext = New PurchaseItem()

    ' Begin an edit transaction that enables
    ' the object to accept or roll back changes.
End Sub

Private Sub Cancel_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    ' Cancel the pending changes and begin a new edit transaction.
End Sub

下面的示例演示了自定义 ValidationRule ValidateDateAndPrice ,它已添加到 BindingGroup 第一个示例中的。The following example shows the custom ValidationRule ValidateDateAndPrice, which was added to the BindingGroup in the first example. ValidationRule BindingGroup 在其方法中使用 Validate 来获取用户在窗体中输入的值,并检查项是否超过100美元,是否可用于至少7天。The ValidationRule uses the BindingGroup in its Validate method to get the values the user entered into the form, and checks that if an item is over 100 dollars, it will be available for at least seven days.

public class ValidateDateAndPrice : ValidationRule
    // Ensure that an item over $100 is available for at least 7 days.
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        BindingGroup bg = value as BindingGroup;

        // Get the source object.
        PurchaseItem item = bg.Items[0] as PurchaseItem;
        object doubleValue;
        object dateTimeValue;

        // Get the proposed values for Price and OfferExpires.
        bool priceResult = bg.TryGetValue(item, "Price", out doubleValue);
        bool dateResult = bg.TryGetValue(item, "OfferExpires", out dateTimeValue);

        if (!priceResult || !dateResult)
            return new ValidationResult(false, "Properties not found");

        double price = (double)doubleValue;
        DateTime offerExpires = (DateTime)dateTimeValue;

        // Check that an item over $100 is available for at least 7 days.
        if (price > 100)
            if (offerExpires < DateTime.Today + new TimeSpan(7, 0, 0, 0))
                return new ValidationResult(false, "Items over $100 must be available for at least 7 days.");

        return ValidationResult.ValidResult;
Public Class ValidateDateAndPrice
    Inherits ValidationRule
    ' Ensure that an item over $100 is available for at least 7 days.
    Public Overrides Function Validate(ByVal value As Object, ByVal cultureInfo As CultureInfo) As ValidationResult
        Dim bg As BindingGroup = TryCast(value, BindingGroup)

        ' Get the source object.
        Dim item As PurchaseItem = TryCast(bg.Items(0), PurchaseItem)

        Dim doubleValue As Object = Nothing
        Dim dateTimeValue As Object = Nothing

        ' Get the proposed values for Price and OfferExpires.
        Dim priceResult As Boolean = bg.TryGetValue(item, "Price", doubleValue)
        Dim dateResult As Boolean = bg.TryGetValue(item, "OfferExpires", dateTimeValue)

        If (Not priceResult) OrElse (Not dateResult) Then
            Return New ValidationResult(False, "Properties not found")
        End If

        Dim price As Double = CDbl(doubleValue)
        Dim offerExpires As Date = CDate(dateTimeValue)

        ' Check that an item over $100 is available for at least 7 days.
        If price > 100 Then
            If offerExpires < Date.Today + New TimeSpan(7, 0, 0, 0) Then
                Return New ValidationResult(False, "Items over $100 must be available for at least 7 days.")
            End If
        End If

        Return ValidationResult.ValidResult

    End Function
End Class


BindingGroup创建多个绑定之间的关系,这些绑定可以同时进行验证和更新。A BindingGroup creates a relationship between multiple bindings, which can be validated and updated together. 例如,假设应用程序提示用户输入地址。For example, suppose that an application prompts the user to enter an address. 然后,应用程序使用用户提供的值填充类型为的对象 Address ,该对象具有属性、 Street 、、 City ZipCodeCountryThe application then populates an object of type Address, which has the properties, Street, City, ZipCode, and Country, with the values that the user provided. 应用程序有一个面板,其中包含四个 TextBox 控件,其中每个控件都绑定到对象的一个属性。The application has a panel that contains four TextBox controls, each of which is data bound to one of the object's properties. 可以 ValidationRule 在中使用 BindingGroup 来验证 Address 对象。You can use a ValidationRule in a BindingGroup to validate the Address object. 如果绑定参与到同一 BindingGroup ,则可以确保邮政编码对地址的国家/地区有效。If the bindings participate in the same BindingGroup, you can ensure that the zip-code is valid for the country/region of the address.

您可以 BindingGroup 在或上设置属性 FrameworkElement FrameworkContentElementYou set the BindingGroup property on FrameworkElement or FrameworkContentElement. 子元素继承 BindingGroup 其父元素,就像任何其他可继承的属性一样。Child elements inherit the BindingGroup from their parent elements, just as with any other inheritable property. 如果发生以下情况之一,则会将子代元素上的绑定添加到 BindingGroupA binding on a descendent element is added to a BindingGroup if one of the following situations occurs:

在地址的示例中,假定的 DataContext Panel 设置为类型的对象 AddressIn the example of the address, suppose that the DataContext of the Panel is set to the object of type Address. 每个的绑定 TextBox 都会添加到面板的中 BindingGroupThe binding for each TextBox is added to the BindingGroup of the panel.

ValidationRule 对象添加到 BindingGroupYou add ValidationRule objects to a BindingGroup. BindingGroup当运行时,将作为方法的第一个参数传递 Validate ValidationRuleThe BindingGroup is passed as the first parameter of the Validate method when the ValidationRule runs. 您可以使用 TryGetValueGetValue(Object, String) 方法 BindingGroup 来获取对象的建议值,并使用 Items 属性来获取绑定的源。You can use the TryGetValue or GetValue(Object, String) method on that BindingGroup to get the proposed values of the object, and the Items property to get the sources of the bindings.

BindingGroup同时更新绑定的源,而不是单独更新每个绑定。A BindingGroup updates the sources of the binding at the same time instead of each binding being updated separately. 当你调用其中一种方法来验证 (ValidateWithoutUpdate 、或) 的数据时 UpdateSources CommitEditTextBox 会验证该示例中每个的绑定,并可能会更新这些绑定。When you call one of the methods to validate the data (ValidateWithoutUpdate, UpdateSources, or CommitEdit), the binding for each TextBox in the example is validated and potentially updated. 当绑定为的一部分时 BindingGroupUpdateSources CommitEdit BindingGroup 除非显式设置了属性,否则直到你调用或上的时,绑定的源才会更新 UpdateSourceTriggerWhen a binding is part of a BindingGroup, the source of the binding is not updated until you call UpdateSources or CommitEdit on the BindingGroup, unless you explicitly set the UpdateSourceTrigger property.



初始化 BindingGroup 类的新实例。Initializes a new instance of the BindingGroup class.



获取 BindingExpression 对象的集合,其中包含有关 BindingGroup 中每个绑定的信息。Gets a collection of BindingExpression objects that contains information for each Binding in the BindingGroup.


获取绑定中的每个源是否都可以放弃挂起的更改并还原原始值。Gets whether each source in the binding can discard pending changes and restore the original values.


获取 DependencyObjectType 包装此实例的 CLR 类型的。Gets the DependencyObjectType that wraps the CLR type of this instance.

(继承自 DependencyObject)

获取与此 Dispatcher 关联的 DispatcherObjectGets the Dispatcher this DispatcherObject is associated with.

(继承自 DispatcherObject)

获取一个值,该值指示 BindingGroup 是否具有一个失败的验证规则。Gets a value that indicates whether the BindingGroup has a failed validation rule.


获取或设置指示 BindingGroup 是否包含尚未写入到源中的建议值的值。Gets or sets a value that indicates whether the BindingGroup contains a proposed value that has not been written to the source.


获取一个值,该值指示此实例当前是否为密封的(只读)。Gets a value that indicates whether this instance is currently sealed (read-only).

(继承自 DependencyObject)

获取 BindingGroup 中的绑定对象所使用的源。Gets the sources that are used by the Binding objects in the BindingGroup.


获取或设置标识 BindingGroup 的名称,该名称可用于在 BindingGroup 中包括和排除绑定对象。Gets or sets the name that identifies the BindingGroup, which can be used to include and exclude Binding objects in the BindingGroup.


获取或设置在 Error 的状态更改时是否发生 ValidationRule 事件。Gets or sets whether the Error event occurs when the state of a ValidationRule changes.


获取 BindingGroup 分配到的对象。Gets the object that this BindingGroup is assigned to.


获取或设置一个值,该值指示 BindingGroup 是否重新使用尚未提交到源的目标值。Gets or sets a value that indicates whether the BindingGroup reuses target values that have not been committed to the source.


获取或设置一个值,该值指示是否包含 NotifyDataErrorValidationRuleGets or sets a value that indicates whether to include the NotifyDataErrorValidationRule.


获取促使 ValidationError 有效的 BindingGroup 对象的集合。Gets a collection of ValidationError objects that caused the BindingGroup to be invalid.


获取 ValidationRule 对象的集合,这些对象验证 BindingGroup 中的源对象。Gets a collection of ValidationRule objects that validate the source objects in the BindingGroup.



开始 BindingGroup 中源上的编辑事务。Begins an edit transaction on the sources in the BindingGroup.


结束编辑事务并放弃挂起的更改。Ends the edit transaction and discards the pending changes.


确定调用线程是否可以访问此 DispatcherObjectDetermines whether the calling thread has access to this DispatcherObject.

(继承自 DispatcherObject)

清除属性的本地值。Clears the local value of a property. 要清除的属性由 DependencyProperty 标识符指定。The property to be cleared is specified by a DependencyProperty identifier.

(继承自 DependencyObject)

清除只读属性的本地值。Clears the local value of a read-only property. 要清除的属性由 DependencyPropertyKey 指定。The property to be cleared is specified by a DependencyPropertyKey.

(继承自 DependencyObject)

对指定依赖属性的值进行强制。Coerces the value of the specified dependency property. 通过对调用方 DependencyObject 上存在的依赖属性的属性元数据中所指定的任何 CoerceValueCallback 函数进行调用来完成此操作。This is accomplished by invoking any CoerceValueCallback function specified in property metadata for the dependency property as it exists on the calling DependencyObject.

(继承自 DependencyObject)

运行所有 ValidationRule 对象,并且在所有验证规则都成功时,更新绑定源。Runs all the ValidationRule objects and updates the binding sources if all validation rules succeed.


确定提供的 DependencyObject 是否等效于当前 DependencyObjectDetermines whether a provided DependencyObject is equivalent to the current DependencyObject.

(继承自 DependencyObject)

获取此 DependencyObject 的哈希代码。Gets a hash code for this DependencyObject.

(继承自 DependencyObject)

创建一个专用的枚举数,用于确定哪些依赖项属性在此 DependencyObject 上具有以本地方式设置的值。Creates a specialized enumerator for determining which dependency properties have locally set values on this DependencyObject.

(继承自 DependencyObject)

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)

DependencyObject 的此实例返回依赖属性的当前有效值。Returns the current effective value of a dependency property on this instance of a DependencyObject.

(继承自 DependencyObject)
GetValue(Object, String)

返回指定的属性和项的建议值。Returns the proposed value for the specified property and item.


重新评估指定依赖属性的有效值。Re-evaluates the effective value for the specified dependency property.

(继承自 DependencyObject)

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)

每当更新此 DependencyObject 的任何依赖属性的有效值时调用。Invoked whenever the effective value of any dependency property on this DependencyObject has been updated. 更改的特定依赖属性将在事件数据中报告。The specific dependency property that changed is reported in the event data.

(继承自 DependencyObject)

如果存在,则返回依赖属性的本地值。Returns the local value of a dependency property, if it exists.

(继承自 DependencyObject)
SetCurrentValue(DependencyProperty, Object)

设置依赖属性的值而不更改其值源。Sets the value of a dependency property without changing its value source.

(继承自 DependencyObject)
SetValue(DependencyProperty, Object)

设置依赖属性的本地值,该值由其依赖属性标识符指定。Sets the local value of a dependency property, specified by its dependency property identifier.

(继承自 DependencyObject)
SetValue(DependencyPropertyKey, Object)

设置一个只读依赖属性的本地值,该值由依赖属性的 DependencyPropertyKey 标识符指定。Sets the local value of a read-only dependency property, specified by the DependencyPropertyKey identifier of the dependency property.

(继承自 DependencyObject)

返回一个值,该值指示序列化进程是否应序列化所提供的依赖属性的值。Returns a value that indicates whether serialization processes should serialize the value for the provided dependency property.

(继承自 DependencyObject)

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)
TryGetValue(Object, String, Object)

尝试获取指定属性和项的建议值。Attempts to get the proposed value for the specified property and item.


如果所有验证规则都成功,则对绑定和将 ValidationRule 属性设置为 ValidationStepRawProposedValueConvertedProposedValueUpdatedValue 对象运行转换器,并将目标值保存到源对象。Runs the converter on the binding and the ValidationRule objects that have the ValidationStep property set to RawProposedValue, ConvertedProposedValue, or UpdatedValue and saves the values of the targets to the source objects if all the validation rules succeed.


对绑定和将 ValidationRule 属性设置为 ValidationStepRawProposedValueConvertedProposedValue 对象运行转换器。Runs the converter on the binding and the ValidationRule objects that have the ValidationStep property set to RawProposedValue or ConvertedProposedValue.


强制调用线程具有此 DispatcherObject 的访问权限。Enforces that the calling thread has access to this DispatcherObject.

(继承自 DispatcherObject)