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)user interface (UI)應用程式的時將它加入根StackPanelBindingGroupCreates a BindingGroup and adds it the root StackPanel when it creates the 使用者介面 (UI)user interface (UI) of the application.

  • BeginEdit應用CommitEdit程式的CancelEdit邏輯中呼叫、和,以啟用回復變更。Calls BeginEdit, CommitEdit, and CancelEdit in the application's logic to enable rolling back changes.

  • 呼叫TryGetValue 方法Validate中的來取得使用者的輸入,然後檢查超過100元的專案是否至少有7天可供使用。Calls TryGetValue in a Validate method to get the user's input and then check that an item over 100 dollars is available for at least seven days.

下列範例會建立使用者介面 (UI)user interface (UI)應用程式的。The following example creates the 使用者介面 (UI)user interface (UI) of the application. StackPanel ValidationRule具有,其中包含驗證專案的,如先前所述。 BindingGroupThe root StackPanel has a BindingGroup that contains a ValidationRule that validates the item, as described previously. Price屬性BindingGroup ValidationRule和屬性上的系結物件會成為的一部分,而每個系結都有,以確保價格和日期分別是有效的值。 OfferExpiresThe 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 BindingGroup上的之前執行。The 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執行與BindingGroup相關聯的每個。When the user clicks the Submit button, the application calls CommitEdit to run each ValidationRule that is associated with the BindingGroup. 如果成功, CommitEdit則會將值儲存至物件,並結束編輯交易。 ValidationRuleIf 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. BindingGroup true NotifyOnValidationError Validation.Error當失敗時,就會發生此事件,因為應用程式會將設定為上的(在上一個範例中為)。 ValidationRuleWhen a ValidationRule fails, the Validation.Error event occurs because the application set NotifyOnValidationError to true on the BindingGroup (in the previous example). ItemErrorValidation.Error處理事件,並向使用者顯示驗證錯誤的相關資訊。ItemError handles the Validation.Error event and displays information about the validation error to the user. 此範例也會處理Loaded的事件StackPanelClick [取消] 按鈕的事件。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. BindingGroup會在其Validate方法中使用,以取得使用者在表單中輸入的值,並檢查如果專案的金額超過100,則會提供至少7天。ValidationRuleThe 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的物件,其具有屬性CityStreet、、 ZipCodeCountry,以及使用者提供的值。The 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 Address在中使用來驗證物件。 BindingGroupYou 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.

您可以在BindingGroupFrameworkContentElementFrameworkElement設定屬性。You 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. BindingGroup如果發生下列其中一種情況,則會將子代元素上的系結新增至:A binding on a descendent element is added to a BindingGroup if one of the following situations occurs:

在位址的範例中,假設DataContext Panel的已設定為類型Address的物件。In the example of the address, suppose that the DataContext of the Panel is set to the object of type Address. 每個TextBox的系結都會新增至BindingGroup面板的。The binding for each TextBox is added to the BindingGroup of the panel.

您可以ValidationRule將物件加入BindingGroup至。You add ValidationRule objects to a BindingGroup. 當執行時Validate BindingGroup ,會傳遞做為方法ValidationRule的第一個參數。The BindingGroup is passed as the first parameter of the Validate method when the ValidationRule runs. 您可以在上TryGetValue GetValue(Object, String) Items使用或方法, BindingGroup以取得物件的建議值,以及用來取得系結來源的屬性。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(、 UpdateSourcesCommitEdit),範例中每個TextBox的系結都會經過驗證,而且可能會更新。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. 當系結為BindingGroup的一部分時,除非您明確設定UpdateSourceTrigger屬性BindingGroup,否則系結的來源UpdateSourcesCommitEdit會更新,直到您在上呼叫或為止。When 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 型別的 CLRCLRGets the DependencyObjectType that wraps the CLRCLR 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 中之 Binding 物件所使用的來源。Gets the sources that are used by the Binding objects in the BindingGroup.


取得或設定名稱,這個名稱會識別用來包含和排除 BindingGroup 中 Binding 物件的 BindingGroupGets 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. 完成方式是叫用存在於呼叫 CoerceValueCallback 之相依性屬性的屬性中繼資料中所指定的任何 DependencyObject 函式。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 和目前的 DependencyObject 是否相等。Determines 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)