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 美元至少有七天可用。
下列範例會建立應用程式 (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 設定 NotifyOnValidationError 為 true
) 。 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
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
物件,其具有使用者所提供的值、、 City
、 ZipCode
和 Country
屬性 Street
。 應用程式有一個面板,其中包含四 TextBox 個控制項,每個控制項都是系結至其中一個物件屬性的資料。 您可以在 中使用 ValidationRuleBindingGroup 來驗證 Address
物件。 如果系結參與相同的 BindingGroup ,您可以確定郵遞區號對位址的國家/地區有效。
您可以在 或 FrameworkContentElement 上 FrameworkElement 設定 BindingGroup 屬性。 子專案繼承 BindingGroup 自其父元素,就像任何其他可繼承的屬性一樣。 如果發生下列其中一種情況,則會將子代專案上的系結新增至 BindingGroup :
系結的來源和 DataContext 具有 BindingGroup 之 專案的 是相同的物件,而且 BindingGroupName 屬性未設定。
系 BindingGroupName 結的 屬性等於 Name 的 BindingGroup ,而且它們不會明確設定為
null
。
在位址的範例中,假設 DataContext 的 Panel 設定為 型 Address
別的物件。 每個 TextBox 的系結都會新增至 BindingGroup 面板的 。
您會將 物件新增 ValidationRule 至 BindingGroup 。 執行 時 ValidationRule ,會 BindingGroup 當做 方法的第一個參數 Validate 傳遞。 您可以使用 TryGetValue 或 GetValue(Object, String) 方法 BindingGroup 來取得物件的建議值,以及 Items 屬性來取得系結的來源。
會 BindingGroup 同時更新系結的來源,而不是個別更新的每個系結。 當您呼叫其中一個方法來驗證資料 (ValidateWithoutUpdate 、 UpdateSources 或 CommitEdit) 時,範例中每個 TextBox 方法的系結都會經過驗證並可能更新。 當系結是 的一 BindingGroup 部分時,除非您明確設定 UpdateSourceTrigger 屬性,否則在您呼叫 UpdateSources 或 CommitEdit 之前 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 中的來源物件。 |
方法
適用於
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應