Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

BindingGroup Class

Contains a collection of bindings and ValidationRule objects that are used to validate an object.

Namespace:  System.Windows.Data
Assembly:  PresentationFramework (in PresentationFramework.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation, http://schemas.microsoft.com/netfx/2007/xaml/presentation

public class BindingGroup : DependencyObject
<BindingGroup .../>

The BindingGroup type exposes the following members.

  NameDescription
Public methodBindingGroupInitializes a new instance of the BindingGroup class.
Top

  NameDescription
Public propertyBindingExpressionsGets a collection of BindingExpression objects that contains information for each Binding in the BindingGroup.
Public propertyCanRestoreValuesGets whether each source in the binding can discard pending changes and restore the original values.
Public propertyDependencyObjectTypeGets the DependencyObjectType that wraps the CLR type of this instance.  (Inherited from DependencyObject.)
Public propertyDispatcherGets the Dispatcher this DispatcherObject is associated with. (Inherited from DispatcherObject.)
Public propertyHasValidationErrorGets a value that indicates whether the BindingGroup has a failed validation rule.
Public propertyIsDirtyGets or sets a value that indicates whether the BindingGroup contains a proposed value that has not been written to the source.
Public propertyIsSealedGets a value that indicates whether this instance is currently sealed (read-only). (Inherited from DependencyObject.)
Public propertyItemsGets the sources that are used by the Binding objects in the BindingGroup.
Public propertyNameGets or sets the name that identifies the BindingGroup, which can be used to include and exclude Binding objects in the BindingGroup.
Public propertyNotifyOnValidationErrorGets or sets whether the Validation.Error event occurs when the state of a ValidationRule changes.
Public propertyOwnerGets the object that this BindingGroup is assigned to.
Public propertySharesProposedValuesGets or sets a value that indicates whether the BindingGroup reuses target values that have not been committed to the source.
Public propertyValidatesOnNotifyDataErrorGets or sets a value that indicates whether to include the NotifyDataErrorValidationRule.
Public propertyValidationErrorsGets a collection of ValidationError objects that caused the BindingGroup to be invalid.
Public propertyValidationRulesGets a collection of ValidationRule objects that validate the source objects in the BindingGroup.
Top

  NameDescription
Public methodBeginEditBegins an edit transaction on the sources in the BindingGroup.
Public methodCancelEditEnds the edit transaction and discards the pending changes.
Public methodCheckAccessDetermines whether the calling thread has access to this DispatcherObject. (Inherited from DispatcherObject.)
Public methodClearValue(DependencyProperty)Clears the local value of a property. The property to be cleared is specified by a DependencyProperty identifier. (Inherited from DependencyObject.)
Public methodClearValue(DependencyPropertyKey)Clears the local value of a read-only property. The property to be cleared is specified by a DependencyPropertyKey. (Inherited from DependencyObject.)
Public methodCoerceValueCoerces the value of the specified dependency property. This is accomplished by invoking any CoerceValueCallback function specified in property metadata for the dependency property as it exists on the calling DependencyObject. (Inherited from DependencyObject.)
Public methodCommitEditRuns all the ValidationRule objects and updates the binding sources if all validation rules succeed.
Public methodEqualsDetermines whether a provided DependencyObject is equivalent to the current DependencyObject. (Inherited from DependencyObject.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeGets a hash code for this DependencyObject. (Inherited from DependencyObject.)
Public methodGetLocalValueEnumeratorCreates a specialized enumerator for determining which dependency properties have locally set values on this DependencyObject. (Inherited from DependencyObject.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetValue(DependencyProperty)Returns the current effective value of a dependency property on this instance of a DependencyObject. (Inherited from DependencyObject.)
Public methodGetValue(Object, String)Returns the proposed value for the specified property and item.
Public methodInvalidatePropertyRe-evaluates the effective value for the specified dependency property (Inherited from DependencyObject.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodOnPropertyChangedInvoked 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. (Inherited from DependencyObject.)
Public methodReadLocalValueReturns the local value of a dependency property, if it exists. (Inherited from DependencyObject.)
Public methodSetCurrentValueSets the value of a dependency property without changing its value source. (Inherited from DependencyObject.)
Public methodSetValue(DependencyProperty, Object)Sets the local value of a dependency property, specified by its dependency property identifier. (Inherited from DependencyObject.)
Public methodSetValue(DependencyPropertyKey, Object)Sets the local value of a read-only dependency property, specified by the DependencyPropertyKey identifier of the dependency property. (Inherited from DependencyObject.)
Protected methodShouldSerializePropertyReturns a value that indicates whether serialization processes should serialize the value for the provided dependency property. (Inherited from DependencyObject.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodTryGetValueAttempts to get the proposed value for the specified property and item.
Public methodUpdateSourcesRuns 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.
Public methodValidateWithoutUpdateRuns the converter on the binding and the ValidationRule objects that have the ValidationStep property set to RawProposedValue or ConvertedProposedValue.
Public methodVerifyAccessEnforces that the calling thread has access to this DispatcherObject. (Inherited from DispatcherObject.)
Top

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. 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. The application has a panel that contains four TextBox controls, each of which is data bound to one of the object’s properties. You can use a ValidationRule in a BindingGroup to validate the Address object. If the bindings participate in the same BindingGroup, you can ensure that the zip-code is valid for the country of the address.

You set the BindingGroup property on FrameworkElement or FrameworkContentElement. Child elements inherit the BindingGroup from their parent elements, just as with any other inheritable property. A binding on a descendent element is added to a BindingGroup if one of the following situations occurs:

In the example of the address, suppose that the DataContext of the Panel is set to the object of type Address. The binding for each TextBox is added to the BindingGroup of the panel.

You add ValidationRule objects to a BindingGroup. The BindingGroup is passed as the first parameter of the Validate method when the ValidationRule runs. 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.

A BindingGroup updates the sources of the binding at the same time instead of each binding being updated separately. 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. 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.

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.

  • Creates a BindingGroup and adds it the root StackPanel when it creates the user interface (UI) of the application. 

  • Calls BeginEdit, CommitEdit, and CancelEdit in the application's logic to enable rolling back changes.

  • 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.

The following example creates the user interface (UI) of the application. The root StackPanel has a BindingGroup that contains a ValidationRule that validates the item, as described previously. 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. The validation rules for the individual properties run before the ValidationRule on the BindingGroup.

<StackPanel Name="stackPanel1"  Margin="10" Width="250"
            Loaded="stackPanel1_Loaded"
            Validation.Error="ItemError">

  <StackPanel.Resources>
    <Style TargetType="HeaderedContentControl">
      <Setter Property="Margin" Value="2"/>
      <Setter Property="Focusable" Value="False"/>
      <Setter Property="Template">
        <Setter.Value>
          <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"/>
            </DockPanel>

          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>

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

    </Style>

  </StackPanel.Resources>

  <StackPanel.BindingGroup>
    <BindingGroup NotifyOnValidationError="True">
      <BindingGroup.ValidationRules>
        <src:ValidateDateAndPrice ValidationStep="ConvertedProposedValue" />
      </BindingGroup.ValidationRules>
    </BindingGroup>
  </StackPanel.BindingGroup>

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

The following example shows the event handlers for the application. When the user clicks the Submit button, the application calls CommitEdit to run each ValidationRule that is associated with the BindingGroup. If each ValidationRule succeeds, CommitEdit saves the values to the object and ends the edit transaction. If CommitEdit is successful, the application begins another edit transaction. When a ValidationRule fails, the Validation.Error event occurs because the application set NotifyOnValidationError to true on the BindingGroup (in the previous example). ItemError handles the Validation.Error event and displays information about the validation error to the user. 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");
                stackPanel1.BindingGroup.BeginEdit();
            }


        }

        // 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)
            {
                MessageBox.Show(e.Error.ErrorContent.ToString());

            }
        }

        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.
            stackPanel1.BindingGroup.BeginEdit();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            // Cancel the pending changes and begin a new edit transaction.
            stackPanel1.BindingGroup.CancelEdit();
            stackPanel1.BindingGroup.BeginEdit();
        }

The following example shows the custom ValidationRule ValidateDateAndPrice, which was added to the BindingGroup in the first example. 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;

    }
}

.NET Framework

Supported in: 4.5, 4, 3.5 SP1, 3.0 SP2

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft