操作說明:實作繫結驗證
此範例示範如何使用 ErrorTemplate 和 樣式觸發程式,根據自定義驗證規則,提供視覺回饋,以在輸入無效值時通知使用者。
範例
下列範例中的 文字內容 TextBox 會系結至 Age
名為 ods
之系結來源對象的 屬性(類型為 int)。 繫結是設為使用名為 AgeRangeRule
的驗證規則,因此如果使用者輸入非數值字元或小於 21 或大於 130 的值,文字方塊旁邊會出現紅色驚嘆號,並在使用者移動滑鼠到文字方塊上方時出現具有錯誤訊息的工具提示。
<TextBox Name="textBox1" Width="50" FontSize="15"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textBoxInError}"
Grid.Row="1" Grid.Column="1" Margin="2">
<TextBox.Text>
<Binding Path="Age" Source="{StaticResource ods}"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<c:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
下列範例示範 的 AgeRangeRule
實作,其繼承自 ValidationRule 並覆寫 Validate 方法。 在 Int32.Parse
值上呼叫 方法,以確定它不包含任何無效的字元。 Validate方法會ValidationResult傳回 ,這個方法會根據剖析期間是否攔截例外狀況,以及年齡值是否超出下限和上限,指出值是否有效。
public class AgeRangeRule : ValidationRule
{
public int Min { get; set; }
public int Max { get; set; }
public AgeRangeRule()
{
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int age = 0;
try
{
if (((string)value).Length > 0)
age = Int32.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, $"Illegal characters or {e.Message}");
}
if ((age < Min) || (age > Max))
{
return new ValidationResult(false,
$"Please enter an age in the range: {Min}-{Max}.");
}
return ValidationResult.ValidResult;
}
}
Public Class AgeRangeRule
Inherits ValidationRule
' Properties
Public Property Max As Integer
Public Property Min As Integer
' Methods
Public Overrides Function Validate(value As Object, cultureInfo As CultureInfo) As ValidationResult
Dim num1 As Integer = 0
Try
If (CStr(value).Length > 0) Then
num1 = Integer.Parse(CStr(value))
End If
Catch exception1 As Exception
Return New ValidationResult(False, $"Illegal characters or {exception1.Message}")
End Try
If ((num1 < Min) OrElse (num1 > Max)) Then
Return New ValidationResult(False, $"Please enter an age in the range: {Min}-{Max}.")
End If
Return ValidationResult.ValidResult
End Function
End Class
下列範例顯示建立紅色驚嘆號的自定義ControlTemplatevalidationTemplate
,以通知使用者驗證錯誤。 控制項樣板是用於重新定義控制項的外觀。
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="20">!</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
如下列範例所示, ToolTip 顯示錯誤訊息的 會使用名為 textBoxInError
的樣式來建立。 如果 值為 HasError true
,則觸發程式會將目前 TextBox 的工具提示設定為其第一個驗證錯誤。 RelativeSource會設定為 Self,參考目前專案。
<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)/ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
如需完整的範例,請參閱 系結驗證範例。
請注意,如果您未提供自定義 ErrorTemplate 的錯誤範本,則會出現在發生驗證錯誤時向使用者提供視覺回饋。 如需詳細資訊,請參閱資料繫結概觀中的<資料驗證>。 此外,WPF 也提供內建的驗證規則,可攔截系結來源屬性更新期間擲回的例外狀況。 如需詳細資訊,請參閱ExceptionValidationRule。