WPF輸入驗證提示
在寫前端輸入時,我們經常要對用戶的輸入進行驗證,檢查輸入的合理性,當輸入非法時,需要能提醒用戶,比如下圖,當輸入不是IP格式的字串時,會提示輸入正確格式的IP,

百度一圈得到的做法:
前端
<TextBox Text="{Binding MccIP,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}" Style="{StaticResource txtboxValiStyle}" BorderThickness="0" Height="30" Margin="5"/>
樣式
<!--textbox驗證style-->
<Style x:Key="txtboxValiStyle" TargetType="TextBox">
<Setter Property="FontSize" Value="https://www.cnblogs.com/slowly-snail/archive/2022/11/16/16"/>
<Setter Property="Height" Value="https://www.cnblogs.com/slowly-snail/archive/2022/11/16/34"/>
<Setter Property="Width" Value="https://www.cnblogs.com/slowly-snail/archive/2022/11/16/140"/>
<Setter Property="Margin" Value="https://www.cnblogs.com/slowly-snail/archive/2022/11/16/3 12 3 0"/>
<Setter Property="VerticalContentAlignment" Value="https://www.cnblogs.com/slowly-snail/archive/2022/11/16/Center"/>
<Setter Property="HorizontalContentAlignment" Value="https://www.cnblogs.com/slowly-snail/archive/2022/11/16/Center"/>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="https://www.cnblogs.com/slowly-snail/archive/2022/11/16/true">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Bottom" Background="Red" Foreground="White" FontSize="12" Height="14"
VerticalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap" FontFamily="Arial"
Text="{Binding ElementName=ErrorBox, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
</TextBlock>
<AdornedElementPlaceholder Name="ErrorBox" />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
在樣式中判斷,Property="Validation.HasError" Value="https://www.cnblogs.com/slowly-snail/archive/2022/11/16/true",觸發樣試更改,
后端
測驗使用的MVVM框架為Caliburn.Micro
using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace DataError.ViewModels
{
public class MainViewModel : Screen, INotifyPropertyChanged, IDataErrorInfo
{
private string mccIP;
[Required]
[RegularExpression(@"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$", ErrorMessage = "請輸入正確格式的IP地址!")]
public string MccIP
{
get { return mccIP; }
set { mccIP = value; NotifyOfPropertyChange(); }
}
#region 實作IDataErrorInfo介面
public string Error
{
get { return null; }
}
public string this[string columnName]
{
get
{
var vc = new ValidationContext(this, null, null);
vc.MemberName = columnName;
var res = new List<ValidationResult>();
var result = Validator.TryValidateProperty(this.GetType().GetProperty(columnName).GetValue(this, null), vc, res);
if (res.Count > 0)
{
return string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
}
return string.Empty;
}
}
#endregion
}
}
首先在ViewModel的類中需繼承IDataErrorInfo介面,并在類中實作IDataErrorInfo介面,然后使用正則運算式判斷字串格式,如果格式不匹配,輸出錯誤訊息,如下圖,

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535108.html
標籤:.NET技术
