[英]Validation when pressing button
我在 ValidationRule 的幫助下在 WPF 中創建了驗證:
public class EmptyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (!string.IsNullOrEmpty(value.ToString()))
{
return new ValidationResult(true, null);
}
return new ValidationResult(false, "Dit veld is verplicht.");
}
}
我像這樣使用它:
<StackPanel Grid.Column="1"
Grid.Row="0"
Margin="10 0 0 20">
<TextBox Width="200"
Height="30"
HorizontalAlignment="Left"
VerticalContentAlignment="Center">
<TextBox.Text>
<Binding Path="Product.ProductName" Mode="TwoWay" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<validators:EmptyValidationRule ValidationStep="RawProposedValue" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<Validation.ErrorTemplate>
<ControlTemplate>
<StackPanel>
<!-- Placeholder for the TextBox itself -->
<AdornedElementPlaceholder x:Name="textBox"/>
<TextBlock Text="{Binding [0].ErrorContent}" Foreground="Red"/>
</StackPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
</StackPanel>
它有效,但不如預期。 例如,如果加載了 windows 並且您使用 Tab 跳轉到下一個字段,則不會顯示消息。 但是當我在該字段中輸入然后將其刪除時,它會顯示該消息。
啟動:
如果我在 TextBox 中單擊並按 Tab,則不會顯示任何消息:
如果我在第一個 TextBox 中再次單擊並鍵入內容,然后再次將其刪除並按 Tab,則會顯示消息:
我怎樣才能解決這個問題? 或者當我單擊按鈕時如何顯示消息?
將ValidationRule
的ValidatesOnTargetUpdated
屬性設置為true
:
<validators:EmptyValidationRule ValidatesOnTargetUpdated="True" ValidationStep="RawProposedValue" />
或者在您的按鈕單擊事件處理程序或另一個事件處理程序中顯式更新綁定的源,例如LostFocus
:
textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
在驗證規則中調用ToString()
之前,不要忘記檢查value
是否為null
:
if (!string.IsNullOrEmpty(value?.ToString()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.