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
繼承

範例

下列範例會建立一個應用程式,提示使用者輸入專案的描述和價格,以及供應專案到期的日期。 應用程式會顯示表單下方專案的目前資訊。 使用者可以提交或取消變更。

應用程式會執行下列動作來達成此行為。

  • 建立 , BindingGroup 並在應用程式) 建立使用者介面 (UI 時,將其新增至根 StackPanel 目錄。

  • 在應用程式的邏輯中呼叫 BeginEditCommitEditCancelEdit ,以啟用復原變更。

  • 在 方法中 Validate 呼叫 TryGetValue 以取得使用者的輸入,然後確認專案超過 100 美元至少有七天可用。

下列範例會建立應用程式 (UI) 的使用者介面。 根 StackPanel 目錄具有 BindingGroup ,其中包含 ValidationRule 驗證專案的 ,如先前所述。 屬性和 屬性上的 Price 系結物件會成為 的 BindingGroup 一部分,而且每個系結都有 ValidationRule ,以確保價格和日期分別是有效的 OfferExpires 值。 個別屬性的驗證規則會在 上的 BindingGroup 之前 ValidationRule 執行。

<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 成功,應用程式就會開始另一個編輯交易。 ValidationRule失敗時,就會發生事件, Validation.Error 因為上一個範例中的應用程式在 (上 BindingGroup 設定 NotifyOnValidationErrortrue) 。 ItemErrorValidation.Error會處理 事件,並向使用者顯示驗證錯誤的相關資訊。 此範例也會處理 Loaded 的 事件 StackPanel ,以及 Click[取消] 按鈕的 事件。


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 ValidationRule會在其 BindingGroup 方法中使用 Validate 來取得使用者輸入表單中的值,並檢查項目是否超過 100 美元,它至少會提供七天。

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 物件,其具有使用者所提供的值、、 CityZipCodeCountry 屬性 Street 。 應用程式有一個面板,其中包含四 TextBox 個控制項,每個控制項都是系結至其中一個物件屬性的資料。 您可以在 中使用 ValidationRuleBindingGroup 來驗證 Address 物件。 如果系結參與相同的 BindingGroup ,您可以確定郵遞區號對位址的國家/地區有效。

您可以在 或 FrameworkContentElementFrameworkElement 設定 BindingGroup 屬性。 子專案繼承 BindingGroup 自其父元素,就像任何其他可繼承的屬性一樣。 如果發生下列其中一種情況,則會將子代專案上的系結新增至 BindingGroup

在位址的範例中,假設 DataContextPanel 設定為 型 Address 別的物件。 每個 TextBox 的系結都會新增至 BindingGroup 面板的 。

您會將 物件新增 ValidationRuleBindingGroup 。 執行 時 ValidationRule ,會 BindingGroup 當做 方法的第一個參數 Validate 傳遞。 您可以使用 TryGetValueGetValue(Object, String) 方法 BindingGroup 來取得物件的建議值,以及 Items 屬性來取得系結的來源。

BindingGroup 同時更新系結的來源,而不是個別更新的每個系結。 當您呼叫其中一個方法來驗證資料 (ValidateWithoutUpdateUpdateSourcesCommitEdit) 時,範例中每個 TextBox 方法的系結都會經過驗證並可能更新。 當系結是 的一 BindingGroup 部分時,除非您明確設定 UpdateSourceTrigger 屬性,否則在您呼叫 UpdateSourcesCommitEdit 之前 BindingGroup ,系結的來源不會更新。

建構函式

BindingGroup()

初始化 BindingGroup 類別的新執行個體。

屬性

BindingExpressions

取得 BindingExpression 物件的集合,這類物件包含 BindingGroup 中各個繫結的資訊。

CanRestoreValues

取得值,這個值表示繫結中的每一個來源是否可以捨棄暫止的變更並還原為原始值。

DependencyObjectType

DependencyObjectType取得包裝這個實例之 CLR 型別的 。

(繼承來源 DependencyObject)
Dispatcher

取得與這個 Dispatcher 關聯的 DispatcherObject

(繼承來源 DispatcherObject)
HasValidationError

取得值,指出 BindingGroup 是否擁有失敗的驗證規則。

IsDirty

取得或設定值,指出 BindingGroup 是否含有尚未寫入至來源的建議值。

IsSealed

取得值,這個值表示此執行個體目前是否已密封 (唯讀)。

(繼承來源 DependencyObject)
Items

取得 BindingGroup 中之 Binding 物件所使用的來源。

Name

取得或設定名稱,這個名稱會識別用來包含和排除 BindingGroup 中 Binding 物件的 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)

適用於