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 사용 하도록 설정 하는 애플리케이션의 논리가 변경 내용 롤백.
호출 TryGetValue 에 Validate 메서드를 사용자의 입력을 가져오고 다음 7 일 이상 100 달러가 넘는 항목을 사용할 수를 확인 합니다.
다음 예제에서는 애플리케이션의 UI(사용자 인터페이스)를 만듭니다. 루트 StackPanel 에 BindingGroup 포함 하는 ValidationRule 앞에서 설명한 대로 항목을 유효성을 검사 하는 합니다. 바인딩 개체를 Price
속성 및 OfferExpires
될 속성 부분 합니다 BindingGroup 각 바인딩에 및를 ValidationRule 있는지 가격 및 날짜를 각각 유효한 값을 합니다. 개별 속성에 대 한 유효성 검사 규칙을 실행 하기 전에 합니다 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 개의 실행 하려면 ValidationRule 연관 된는 BindingGroup합니다. 경우 각 ValidationRule 성공 하면 CommitEdit 편집 트랜잭션을 끝내 고 개체에 값을 저장 합니다. 경우 CommitEdit 가 성공 하면 애플리케이션이 다른 편집 트랜잭션을 시작 합니다. 경우는 ValidationRule 실패 하면를 Validation.Error 애플리케이션 설정 때문에 이벤트가 발생 NotifyOnValidationError 를 true
에 BindingGroup (이전 예제의). 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
다음 예제에서는 첫 번째 예제에서 추가된 사용자 지정 ValidationRule ValidateDateAndPrice
을 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 컨트롤을 각각 데이터가 개체의 속성 중 하나에 바인딩됩니다. 사용할 수는 ValidationRule 에 BindingGroup 유효성을 검사 하는 Address
개체. 바인딩이 동일한 BindingGroup항목에 참여하는 경우 주소의 국가/지역에 대해 우편 번호가 유효한지 확인할 수 있습니다.
설정 된 BindingGroup 속성을 FrameworkElement 또는 FrameworkContentElement합니다. 자식 요소에서 상속 된 BindingGroup 다른 상속 가능한 속성에서와 마찬가지로 해당 부모 요소에서. 에 하위 요소를 바인딩에 추가 되는 BindingGroup 다음 상황 중 하나가 발생 하는 경우:
바인딩의 소스 및 DataContext 있는 요소를 BindingGroup 가 같은 개체 및 BindingGroupName 속성이 설정 되지 않았습니다.
BindingGroupName 바인딩의 속성 값과 같음 합니다 Name 의 BindingGroup 명시적으로 설정 되지 않은 및
null
합니다.
주소의 예 된다고 가정 합니다 DataContext 의 Panel 형식의 개체로 설정 됩니다 Address
합니다. 각각에 대 한 바인딩을 TextBox 에 추가 되는 BindingGroup 패널의 합니다.
추가한 ValidationRule 개체는 BindingGroup합니다. 합니다 BindingGroup 의 첫 번째 매개 변수로 전달 되는 Validate 메서드 때는 ValidationRule 실행 합니다. 사용할 수는 TryGetValue 또는 GetValue(Object, String) 메서드를 BindingGroup 개체의 제안 된 값을 가져옵니다 및 Items 바인딩의 소스를 가져올 속성입니다.
BindingGroup 개별적으로 업데이트 되 고 각 바인딩하는 대신 동시 바인딩 소스를 업데이트 합니다. 데이터의 유효성을 검사 하는 방법 중 하나를 호출 하는 경우 (ValidateWithoutUpdate, UpdateSources, 또는 CommitEdit), 각각에 대 한 바인딩을 TextBox 의 예에서는 유효성 검사 및 잠재적으로 업데이트 합니다. 바인딩을의 일부인 경우는 BindingGroup를 바인딩 소스를 호출할 때까지 업데이트 되지 않습니다 UpdateSources 또는 CommitEdit 에 BindingGroup명시적으로 설정 되지 않은 경우는 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 개체의 컬렉션을 가져옵니다. |