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 を追加します。

  • アプリケーションのロジックで 、CommitEdit、および CancelEdit を呼び出BeginEditして、ロールバックの変更を有効にします。

  • メソッドで Validate を呼び出TryGetValueしてユーザーの入力を取得し、100 ドルを超えるアイテムが少なくとも 7 日間使用可能であることをチェックします。

次の例では、アプリケーションのユーザー インターフェイス (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 、アプリケーションは別の編集トランザクションを開始します。 ValidationRuleが失敗すると、(前のValidation.Error例の) でアプリケーションが にtrueBindingGroup 設定NotifyOnValidationErrorされているため、イベントが発生します。 ItemError はイベントを Validation.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を示しています。 ではValidationRuleValidate メソッドで を使用BindingGroupして、ユーザーがフォームに入力した値を取得し、アイテムが 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のオブジェクトに、ZipCodeStreetCityユーザーが指定した値を設定します。Country アプリケーションには 4 つの TextBox コントロールを含むパネルがあり、それぞれがオブジェクトのプロパティのいずれかにバインドされたデータです。 内の BindingGroupValidationRule使用して、オブジェクトをAddress検証できます。 バインドが同じ BindingGroupに参加している場合は、郵便番号が住所の国/地域に対して有効であることを確認できます。

プロパティは、 BindingGroup または FrameworkContentElementFrameworkElement設定します。 子要素は、他の BindingGroup 継承可能なプロパティと同様に、親要素から を継承します。 次のいずれかの状況が発生した場合、子孫要素のバインドが に BindingGroup 追加されます。

アドレスの例では、 の Panel が 型Addressのオブジェクトに設定されているDataContextとします。 それぞれの TextBox バインドがパネルの の BindingGroup に追加されます。

オブジェクトを にBindingGroup追加ValidationRuleします。 BindingGroupは、 の実行時ValidationRuleに メソッドの最初のValidateパラメーターとして渡されます。 または BindingGroup メソッドをTryGetValueGetValue(Object, String)使用して、オブジェクトの提案された値を取得し、 プロパティをItems使用してバインディングのソースを取得できます。

では BindingGroup 、各バインディングが個別に更新されるのではなく、バインドのソースが同時に更新されます。 いずれかのメソッドを呼び出してデータ (ValidateWithoutUpdate、、またはCommitEdit) を検証すると、UpdateSources例の各TextBoxバインディングが検証され、更新される可能性があります。 バインドが のBindingGroup一部である場合、 プロパティを明示的に設定しない限り、 または CommitEditBindingGroup呼び出UpdateSourcesすまで、バインディングのソースは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 プロパティが ValidationStepRawProposedValue、または ConvertedProposedValue に設定されている UpdatedValue オブジェクトに対してコンバーターを実行し、すべての検証ルールが成功した場合は、ターゲットの値をソース オブジェクトに保存します。

ValidateWithoutUpdate()

バインディングおよび ValidationRule プロパティが ValidationStep または RawProposedValue に設定されている ConvertedProposedValue オブジェクトに対し、コンバーターを実行します。

VerifyAccess()

呼び出し元のスレッドがこの DispatcherObject にアクセスできるように強制します。

(継承元 DispatcherObject)

適用対象