BindingGroup 类

定义

包含绑定集合和用于验证对象的 ValidationRule 对象。

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

示例

以下示例创建一个应用程序,该应用程序提示用户输入商品的说明和价格以及产品/服务到期日期。 应用程序显示窗体下方项的当前信息。 用户可以提交或取消更改。

应用程序执行以下操作来实现此行为。

以下示例在应用程序的 UI) (创建用户界面。 根 StackPanel 具有一个 BindingGroup ,其中包含 ValidationRule 用于验证项的 ,如前所述。 属性和 属性上的Price绑定对象将成为 的BindingGroup一部分,每个绑定都有 ,ValidationRule以确保价格和日期分别是有效的OfferExpires值。 各个属性ValidationRule的验证规则在 上运行。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>

以下示例演示应用程序的事件处理程序。 当用户单击“提交”按钮时,应用程序将调用 CommitEdit 以运行与 BindingGroup关联的每个 ValidationRule 。 如果每个 ValidationRule 操作都成功, CommitEdit 请将值保存到 对象并结束编辑事务。 如果 CommitEdit 成功,应用程序将开始另一个编辑事务。 失败时,Validation.Error由于应用程序在上一个ValidationRule示例中的 (上设置为 BindingGroupNotifyOnValidationErrortrue) ,因此会发生 该事件。 ItemErrorValidation.Error处理 事件,并向用户显示有关验证错误的信息。 该示例还处理 Loaded 的事件和 StackPanelClick取消 按钮的事件。


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();
}

Private Sub Submit_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If stackPanel1.BindingGroup.CommitEdit() Then
        MessageBox.Show("Item submitted")
        stackPanel1.BindingGroup.BeginEdit()
    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
        MessageBox.Show(e.Error.ErrorContent.ToString())

    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.
    stackPanel1.BindingGroup.BeginEdit()
End Sub

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

以下示例演示在第一个示例中添加到 BindingGroup 的自定义 。ValidationRuleValidateDateAndPrice ValidationRuleBindingGroup在其Validate方法中使用 来获取用户在表单中输入的值,并检查如果某个项超过 100 美元,则至少可以使用 7 天。

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 多个绑定之间创建一个关系,这些绑定可以一起验证和更新。 例如,假设应用程序提示用户输入地址。 然后,应用程序使用用户提供的值填充类型 Address为 的对象,该对象具有属性 StreetCityZipCodeCountry。 该应用程序有一个面板,其中包含四 TextBox 个控件,每个控件都是绑定到对象的一个属性的数据。 可以使用 ValidationRule 中的 BindingGroup 来验证 Address 对象。 如果绑定参与同一 BindingGroup个 ,则可以确保邮政编码对地址的国家/地区有效。

在 或 FrameworkContentElementFrameworkElement设置 BindingGroup 属性。 子元素从其父元素继承 , BindingGroup 就像任何其他可继承属性一样。 如果发生以下情况之一,则会将子元素上的绑定添加到 中 BindingGroup

在地址的示例中,假设 DataContextPanel 设置为 类型的 Address对象。 每个TextBox的绑定将添加到面板的 。BindingGroup

将 对象添加到 ValidationRuleBindingGroup。 运行时,将BindingGroup作为 方法ValidationRule的第一个参数Validate传递。 可以使用 TryGetValueGetValue(Object, String) 或 方法获取 BindingGroup 对象的建议值,并使用 Items 属性获取绑定的源。

BindingGroup同时更新绑定的源,而不是单独更新每个绑定。 调用方法之一来验证 (ValidateWithoutUpdateUpdateSourcesCommitEdit) 的数据时,示例中每个 TextBox 方法的绑定都会得到验证并可能更新。 当绑定是 的一部分时 BindingGroup,除非显式设置 属性,否则在调用 UpdateSourcesCommitEditBindingGroup之前不会更新绑定的 UpdateSourceTrigger 源。

构造函数

BindingGroup()

初始化 BindingGroup 类的新实例。

属性

BindingExpressions

获取 BindingExpression 对象的集合,其中包含有关 BindingGroup 中每个绑定的信息。

CanRestoreValues

获取绑定中的每个源是否都可以放弃挂起的更改并还原原始值。

DependencyObjectType

DependencyObjectType获取包装此实例的 CLR 类型的 。

(继承自 DependencyObject)
Dispatcher

获取与此 Dispatcher 关联的 DispatcherObject

(继承自 DispatcherObject)
HasValidationError

获取一个值,该值指示 BindingGroup 是否具有一个失败的验证规则。

IsDirty

获取或设置指示 BindingGroup 是否包含尚未写入到源中的建议值的值。

IsSealed

获取一个值,该值指示此实例当前是否为密封的(只读)。

(继承自 DependencyObject)
Items

获取 BindingGroup 中的绑定对象所使用的源。

Name

获取或设置标识 BindingGroup 的名称,该名称可用于在 BindingGroup 中包括和排除绑定对象。

NotifyOnValidationError

获取或设置在 Error 的状态更改时是否发生 ValidationRule 事件。

Owner

获取 BindingGroup 分配到的对象。

SharesProposedValues

获取或设置一个值,该值指示 BindingGroup 是否重新使用尚未提交到源的目标值。

ValidatesOnNotifyDataError

获取或设置一个值,该值指示是否包含 NotifyDataErrorValidationRule

ValidationErrors

获取促使 ValidationError 有效的 BindingGroup 对象的集合。

ValidationRules

获取 ValidationRule 对象的集合,这些对象验证 BindingGroup 中的源对象。

方法

BeginEdit()

开始 BindingGroup 中源上的编辑事务。

CancelEdit()

结束编辑事务并放弃挂起的更改。

CheckAccess()

确定调用线程是否可以访问此 DispatcherObject

(继承自 DispatcherObject)
ClearValue(DependencyProperty)

清除属性的本地值。 要清除的属性由 DependencyProperty 标识符指定。

(继承自 DependencyObject)
ClearValue(DependencyPropertyKey)

清除只读属性的本地值。 要清除的属性由 DependencyPropertyKey 指定。

(继承自 DependencyObject)
CoerceValue(DependencyProperty)

对指定依赖属性的值进行强制。 通过对调用方 DependencyObject 上存在的依赖属性的属性元数据中所指定的任何 CoerceValueCallback 函数进行调用来完成此操作。

(继承自 DependencyObject)
CommitEdit()

运行所有 ValidationRule 对象,并且在所有验证规则都成功时,更新绑定源。

Equals(Object)

确定提供的 DependencyObject 是否等效于当前 DependencyObject

(继承自 DependencyObject)
GetHashCode()

获取此 DependencyObject 的哈希代码。

(继承自 DependencyObject)
GetLocalValueEnumerator()

创建一个专用的枚举数,用于确定哪些依赖项属性在此 DependencyObject 上具有以本地方式设置的值。

(继承自 DependencyObject)
GetType()

获取当前实例的 Type

(继承自 Object)
GetValue(DependencyProperty)

DependencyObject 的此实例返回依赖属性的当前有效值。

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

返回指定的属性和项的建议值。

InvalidateProperty(DependencyProperty)

重新评估指定依赖属性的有效值。

(继承自 DependencyObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
OnPropertyChanged(DependencyPropertyChangedEventArgs)

每当更新此 DependencyObject 的任何依赖属性的有效值时调用。 更改的特定依赖属性将在事件数据中报告。

(继承自 DependencyObject)
ReadLocalValue(DependencyProperty)

如果存在,则返回依赖属性的本地值。

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

设置依赖属性的值而不更改其值源。

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

设置依赖属性的本地值,该值由其依赖属性标识符指定。

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

设置一个只读依赖属性的本地值,该值由依赖属性的 DependencyPropertyKey 标识符指定。

(继承自 DependencyObject)
ShouldSerializeProperty(DependencyProperty)

返回一个值,该值指示序列化进程是否应序列化所提供的依赖属性的值。

(继承自 DependencyObject)
ToString()

返回表示当前对象的字符串。

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

尝试获取指定属性和项的建议值。

UpdateSources()

如果所有验证规则都成功,则对绑定和将 ValidationRule 属性设置为 ValidationStepRawProposedValueConvertedProposedValueUpdatedValue 对象运行转换器,并将目标值保存到源对象。

ValidateWithoutUpdate()

对绑定和将 ValidationRule 属性设置为 ValidationStepRawProposedValueConvertedProposedValue 对象运行转换器。

VerifyAccess()

强制调用线程具有此 DispatcherObject 的访问权限。

(继承自 DispatcherObject)

适用于