BindingGroup 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
개체의 유효성을 검사하는 데 사용되는 바인딩 및 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 호출하여 변경 내용을 롤백할 수 있도록 합니다.
Validate 메서드에서 TryGetValue 호출하여 사용자의 입력을 받고 100달러가 넘는 항목을 최소 7일 동안 사용할 수 있는지 확인합니다.
다음 예제에서는 애플리케이션의 UI(사용자 인터페이스)를 만듭니다. 루트 StackPanel 앞에서 설명한 대로 항목의 유효성을 검사하는 ValidationRule 포함하는 BindingGroup 있습니다.
Price 속성 및 OfferExpires 속성의 바인딩 개체는 BindingGroup 일부가 되며 각 바인딩에는 가격과 날짜가 각각 유효한 값인지 확인하는 ValidationRule 있습니다. 개별 속성에 대한 유효성 검사 규칙은 BindingGroupValidationRule 전에 실행됩니다.
<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 실패하면 애플리케이션 집합이 이전 예제의 BindingGrouptrueNotifyOnValidationError 때문에 Validation.Error 이벤트가 발생합니다.
ItemError
Validation.Error 이벤트를 처리하고 유효성 검사 오류에 대한 정보를 사용자에게 표시합니다. 이 예제에서는 StackPanel 대한 Loaded 이벤트와 취소 단추에 대한 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
Validate 메서드의 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 유효성을 검사하고 함께 업데이트할 수 있는 여러 바인딩 간의 관계를 만듭니다. 예를 들어 애플리케이션에서 사용자에게 주소를 입력하라는 메시지를 표시한다고 가정합니다. 그런 다음 애플리케이션은 속성, Street, City, ZipCode및 CountryAddress형식의 개체를 사용자가 제공한 값으로 채웁니다. 애플리케이션에는 4개의 TextBox 컨트롤이 포함된 패널이 있으며, 각 컨트롤은 개체의 속성 중 하나에 바인딩된 데이터입니다.
BindingGroup
ValidationRule 사용하여 Address 개체의 유효성을 검사할 수 있습니다. 바인딩이 동일한 BindingGroup참여하는 경우 주소의 국가/지역에 대해 우편 번호가 유효한지 확인할 수 있습니다.
FrameworkElement 또는 FrameworkContentElementBindingGroup 속성을 설정합니다. 자식 요소는 다른 상속 가능한 속성과 마찬가지로 부모 요소에서 BindingGroup 상속합니다. 다음 상황 중 하나가 발생하는 경우 하위 요소의 바인딩이 BindingGroup 추가됩니다.
바인딩의 원본 및 BindingGroup 있는 요소의 DataContext 동일한 개체이며 BindingGroupName 속성이 설정되지 않았습니다.
바인딩의 BindingGroupName 속성은 BindingGroupName 같으며 명시적으로
null설정되지 않았습니다.
주소 예제에서 PanelDataContextAddress형식의 개체로 설정한다고 가정합니다. 각 TextBox 대한 바인딩이 패널의 BindingGroup 추가됩니다.
BindingGroup ValidationRule 개체를 추가합니다. BindingGroup ValidationRule 실행할 때 Validate 메서드의 첫 번째 매개 변수로 전달됩니다. 해당 BindingGroupTryGetValue 또는 GetValue(Object, String) 메서드를 사용하여 개체의 제안된 값을 가져올 수 있고 Items 속성을 사용하여 바인딩의 원본을 가져올 수 있습니다.
BindingGroup 각 바인딩이 별도로 업데이트되는 대신 바인딩의 원본을 동시에 업데이트합니다. 메서드 중 하나를 호출하여 데이터(ValidateWithoutUpdate, UpdateSources또는 CommitEdit)의 유효성을 검사할 때 예제의 각 TextBox 대한 바인딩이 유효성을 검사하고 잠재적으로 업데이트됩니다. 바인딩이 BindingGroup일부인 경우 UpdateSourceTrigger 속성을 명시적으로 설정하지 않는 한 BindingGroupUpdateSources 또는 CommitEdit 호출할 때까지 바인딩의 원본이 업데이트되지 않습니다.
생성자
| BindingGroup() |
BindingGroup 클래스의 새 인스턴스를 초기화합니다. |
속성
| BindingExpressions |
BindingGroup각 Binding에 대한 정보를 포함하는 BindingExpression 개체의 컬렉션을 가져옵니다. |
| CanRestoreValues |
바인딩의 각 원본이 보류 중인 변경 내용을 취소하고 원래 값을 복원할 수 있는지 여부를 가져옵니다. |
| DependencyObjectType |
이 인스턴스의 CLR 형식을 래핑하는 DependencyObjectType 가져옵니다. (다음에서 상속됨 DependencyObject) |
| Dispatcher |
이 DispatcherObject 연결된 Dispatcher 가져옵니다. (다음에서 상속됨 DispatcherObject) |
| HasValidationError |
BindingGroup 실패한 유효성 검사 규칙이 있는지 여부를 나타내는 값을 가져옵니다. |
| IsDirty |
BindingGroup 소스에 기록되지 않은 제안된 값이 포함되어 있는지 여부를 나타내는 값을 가져오거나 설정합니다. |
| IsSealed |
이 인스턴스가 현재 봉인되어 있는지 여부를 나타내는 값을 가져옵니다(읽기 전용). (다음에서 상속됨 DependencyObject) |
| Items |
BindingGroupBinding 개체에서 사용하는 소스를 가져옵니다. |
| Name |
BindingGroup바인딩 개체를 포함하고 제외하는 데 사용할 수 있는 BindingGroup식별하는 이름을 가져오거나 설정합니다. |
| NotifyOnValidationError |
ValidationRule 상태가 변경되면 Error 이벤트가 발생하는지 여부를 가져오거나 설정합니다. |
| Owner |
이 BindingGroup 할당된 개체를 가져옵니다. |
| SharesProposedValues |
BindingGroup 원본에 커밋되지 않은 대상 값을 다시 사용할지 여부를 나타내는 값을 가져오거나 설정합니다. |
| ValidatesOnNotifyDataError |
NotifyDataErrorValidationRule포함할지 여부를 나타내는 값을 가져오거나 설정합니다. |
| ValidationErrors |
BindingGroup 유효하지 않은 ValidationError 개체의 컬렉션을 가져옵니다. |
| ValidationRules |
BindingGroup소스 개체의 유효성을 검사하는 ValidationRule 개체의 컬렉션을 가져옵니다. |