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 에 추가합니다.

  • 호출 BeginEdit, CommitEdit, 및 CancelEdit 사용 하도록 설정 하는 애플리케이션의 논리가 변경 내용 롤백.

  • 호출 TryGetValueValidate 메서드를 사용자의 입력을 가져오고 다음 7 일 이상 100 달러가 넘는 항목을 사용할 수를 확인 합니다.

다음 예제에서는 애플리케이션의 UI(사용자 인터페이스)를 만듭니다. 루트 StackPanelBindingGroup 포함 하는 ValidationRule 앞에서 설명한 대로 항목을 유효성을 검사 하는 합니다. 바인딩 개체를 Price 속성 및 OfferExpires 될 속성 부분 합니다 BindingGroup 각 바인딩에 및를 ValidationRule 있는지 가격 및 날짜를 각각 유효한 값을 합니다. 개별 속성에 대 한 유효성 검사 규칙을 실행 하기 전에 합니다 ValidationRuleBindingGroup합니다.

<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 개의 실행 하려면 ValidationRule 연관 된는 BindingGroup합니다. 경우 각 ValidationRule 성공 하면 CommitEdit 편집 트랜잭션을 끝내 고 개체에 값을 저장 합니다. 경우 CommitEdit 가 성공 하면 애플리케이션이 다른 편집 트랜잭션을 시작 합니다. 경우는 ValidationRule 실패 하면를 Validation.Error 애플리케이션 설정 때문에 이벤트가 발생 NotifyOnValidationErrortrueBindingGroup (이전 예제의). ItemError 핸들을 Validation.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

다음 예제에서는 사용자 지정 ValidationRuleValidateDateAndPrice에 추가 됨을 BindingGroup 첫 번째 예제에서입니다. ValidationRule 사용 하 여는 BindingGroup 에서 해당 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에 속성이 Street, City, ZipCode, 및 Country, 사용자가 제공한 값을 사용 하 여 합니다. 애플리케이션에 4 개를 포함 하는 패널 TextBox 컨트롤을 각각 데이터가 개체의 속성 중 하나에 바인딩됩니다. 사용할 수는 ValidationRuleBindingGroup 유효성을 검사 하는 Address 개체. 바인딩이 동일한 BindingGroup에 참여하는 경우 주소의 국가/지역에 대해 우편 번호가 유효한지 확인할 수 있습니다.

설정 된 BindingGroup 속성을 FrameworkElement 또는 FrameworkContentElement합니다. 자식 요소에서 상속 된 BindingGroup 다른 상속 가능한 속성에서와 마찬가지로 해당 부모 요소에서. 에 하위 요소를 바인딩에 추가 되는 BindingGroup 다음 상황 중 하나가 발생 하는 경우:

주소의 예 된다고 가정 합니다 DataContextPanel 형식의 개체로 설정 됩니다 Address합니다. 각각에 대 한 바인딩을 TextBox 에 추가 되는 BindingGroup 패널의 합니다.

추가한 ValidationRule 개체는 BindingGroup합니다. 합니다 BindingGroup 의 첫 번째 매개 변수로 전달 되는 Validate 메서드 때는 ValidationRule 실행 합니다. 사용할 수는 TryGetValue 또는 GetValue(Object, String) 메서드를 BindingGroup 개체의 제안 된 값을 가져옵니다 및 Items 바인딩의 소스를 가져올 속성입니다.

BindingGroup 개별적으로 업데이트 되 고 각 바인딩하는 대신 동시 바인딩 소스를 업데이트 합니다. 데이터의 유효성을 검사 하는 방법 중 하나를 호출 하는 경우 (ValidateWithoutUpdate, UpdateSources, 또는 CommitEdit), 각각에 대 한 바인딩을 TextBox 의 예에서는 유효성 검사 및 잠재적으로 업데이트 합니다. 바인딩을의 일부인 경우는 BindingGroup를 바인딩 소스를 호출할 때까지 업데이트 되지 않습니다 UpdateSources 또는 CommitEditBindingGroup명시적으로 설정 되지 않은 경우는 UpdateSourceTrigger 속성.

생성자

BindingGroup()

BindingGroup 클래스의 새 인스턴스를 초기화합니다.

속성

BindingExpressions

BindingExpression의 각 바인딩에 대한 정보가 들어 있는 BindingGroup 개체의 컬렉션을 가져옵니다.

CanRestoreValues

바인딩의 각 소스에서 보류 중인 변경 내용을 삭제하고 원래 값을 복원할 수 있는지 여부를 가져옵니다.

DependencyObjectType

DependencyObjectType 이 instance 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)

serialization 프로세스에서 지정된 종속성 속성의 값을 직렬화해야 하는지 여부를 나타내는 값을 반환합니다.

(다음에서 상속됨 DependencyObject)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
TryGetValue(Object, String, Object)

지정된 속성 및 항목에 대해 제안된 값을 가져오려고 시도합니다.

UpdateSources()

ValidationRule 속성이 ValidationStep, RawProposedValue 또는 ConvertedProposedValue로 설정된 UpdatedValue 개체 및 바인딩에 대해 변환기를 실행하고 모든 유효성 검사 규칙이 성공하는 경우 대상의 값을 소스 개체에 저장합니다.

ValidateWithoutUpdate()

ValidationRule 속성이 ValidationStep 또는 RawProposedValue로 설정된 ConvertedProposedValue 개체 및 바인딩에 대해 변환기를 실행합니다.

VerifyAccess()

호출 스레드에서 이 DispatcherObject에 액세스할 수 있는지 확인합니다.

(다음에서 상속됨 DispatcherObject)

적용 대상