引言
在WPF應用程序開發(fā)中,數(shù)據(jù)校驗是確保用戶輸入數(shù)據(jù)的正確性和完整性的重要一環(huán)。
之前在做一些參數(shù)配置功能時,最是頭疼各種參數(shù)校驗,查閱一些資料后,我總結(jié)了數(shù)據(jù)校驗方式有兩種:
- ValidationRule
- IDataErrorInfo
接下來分別介紹這兩種校驗方式。
ValidationRule
ValidationRule
是一個抽象類,提供了抽象方法 Validate()
, 它是WPF中用于數(shù)據(jù)驗證的一種機制,它可以在用戶輸入數(shù)據(jù)之前或之后執(zhí)行自定義的驗證邏輯。可以輕松地實現(xiàn)對數(shù)據(jù)的格式、范圍、邏輯等方面的驗證,并在驗證失敗時提供相應的反饋信息。
ValidationRule主要作用域在前端頁面上。
基本用法
首先創(chuàng)建一個 ValidationRule
,我這里設定了兩個屬性 MaxVal
、MinVal
,然后在 Validate()
方法中判斷空、判斷大于上限或小于下限,然后在符合條件是,返回 ValidationResult
,并給出錯誤提示:
public class IntegerValidationRule : ValidationRule
{
public int MaxVal { get; set; }
public int MinVal { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string text = value as string;
if (!int.TryParse(text, out int result))
{
return new ValidationResult(false, "Text cannot be empty.");
}
if (result > MaxVal)
{
return new ValidationResult(false, "Value out of upper limit range.");
}
if (result < MinVal)
{
return new ValidationResult(false, "Value out of lower limit range.");
}
return ValidationResult.ValidResult;
}
}
接下來創(chuàng)建有個測試使用的 ViewModel
:
public class TestViewModel : INotifyPropertyChanged
{
private TestViewModel() { }
public static TestViewModel Instance { get; } = new TestViewModel();
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private int testField1;
/// <summary>
/// 測試屬性1
/// </summary>
public int TestField1
{
get => testField1;
set
{
testField1 = value;
OnPropertyChanged(nameof(TestField1));
}
}
private int testField2;
/// <summary>
/// 測試屬性2
/// </summary>
public int TestField2
{
get => testField2;
set
{
testField2 = value;
OnPropertyChanged(nameof(TestField2));
}
}
}
在測試之前,我們可以先看一下 Binding
的方法列表:
可以看到 ValidationRules
是 Binding
下的集合,這意味著 ValidationRule
是在 Binding
下使用且可以執(zhí)行多個校驗規(guī)則。校驗時按照順序依次校驗。
接下來我們創(chuàng)建一個WPF應用程序,在界面添加 TextBox
,命名為”textbox1“,將文本綁定在 TestViewModel
的 TestField1
。
且為Validation.ErrorTemplate
綁定一個模板,這里綁定了一個紅色的感嘆號。
然后為 TextBox
設置觸發(fā)器,當 Validation.HasError
為 true
時,將 ToolTip
綁定校驗失敗的錯誤提示。
代碼如下:
<Window
x:Class="WpfApp4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp4"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="900"
Height="450"
mc:Ignorable="d">
<Window.Resources>
<ControlTemplate x:Key="ValidationTemplate">
<DockPanel>
<TextBlock
Margin="-10,0,0,0"
VerticalAlignment="Center"
FontSize="22"
Foreground="Red"
Text="!" />
</DockPanel>
</ControlTemplate>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<TextBlock
HorizontalAlignment="Center"
FontSize="18"
FontWeight="Bold"
Text="Validation Demo" />
<TextBox
Name="textBox1"
Height="30"
Margin="10"
FontSize="22"
Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
<TextBox.Text>
<Binding Path="TestField1" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:IntegerValidationRule
MaxVal="999"
MinVal="5" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</StackPanel>
</Grid>
</Window>
最后在窗體后臺綁定 ViewModel
:
public MainWindow()
{
InitializeComponent();
this.DataContext = TestViewModel.Instance;
}
測試
-
為空時,出現(xiàn)紅色嘆號,
ToolTip
提示 "Text cannot be empty." -
小于下限時,出現(xiàn)紅色嘆號,
ToolTip
提示 "Value out of lower limit range." -
大于上限時,出現(xiàn)紅色嘆號,
ToolTip
提示 "Value out of upper limit range."
IDataErrorInfo
IDataErrorInfo
是一個接口,Viewmodel 實現(xiàn)接口用于在后臺,提供數(shù)據(jù)驗證和錯誤信息。
IDataErrorInfo
主要作用域為后臺 ViewModel
該接口包含兩個成員:Error
和 this[string columnName]
。這兩個成員允許你在數(shù)據(jù)綁定時提供驗證錯誤信息。
基本用法
接下來,在程序里添加 TextBox
,命名為”textbox2“,并添加一個 TextBlock
綁定 Error
展示在界面。
<StackPanel Grid.Column="1">
<TextBlock
HorizontalAlignment="Center"
FontSize="18"
FontWeight="Bold"
Text="IDataErrorInfo Demo" />
<TextBox
Name="textBox2"
Margin="10"
VerticalAlignment="Center"
FontSize="22"
Text="{Binding TestField2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
<TextBlock
HorizontalAlignment="Center"
FontSize="18"
FontWeight="Bold"
Foreground="Red"
Text="{Binding Error, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
后臺 TestViweModel
實現(xiàn) IDataErrorInfo
,依舊是判斷上限值和下限值,此處不判斷空,是因為后臺 TestField2
類型是Int,為空時不會賦值,代碼如下:
public class TestViewModel : INotifyPropertyChanged, IDataErrorInfo
{
//省略上文已有代碼..。
private string error;
public string Error
{
get => error;
set
{
error = value; OnPropertyChanged(nameof(Error));
}
}
public string this[string columnName]
{
get
{
switch (columnName)
{
case nameof(TestField2):
return CheckTestFild2();
default:
return null;
}
}
}
public int MaxVal = 999;
public int MinVal = 5;
private string CheckTestFild2()
{
if (TestField2 > MaxVal)
{
Error = "Value out of upper limit range in viewmodel.";
}
else if (TestField2 < MinVal)
{
Error = "Value out of lower limit range in viewmodel.";
}
else
{
Error = string.Empty;
}
return Error;
}
}
測試
-
小于下限時,出現(xiàn)紅色文字提示,
ToolTip
提示 "Value out of lower limit range in viewmodel." -
大于上限時,出現(xiàn)紅色文字提示,
ToolTip
提示 "Value out of upper limit range in viewmodel."
小結(jié)
以上兩種數(shù)據(jù)校驗(IDataErrorInfo
、ValidationRule
)的方式,均可以實現(xiàn)自定義數(shù)據(jù)校驗,例如對數(shù)據(jù)的格式、范圍、邏輯等方面的驗證,并在驗證失敗時提供相應的反饋信息。
ValidationRule
適用于在界面做數(shù)據(jù)校驗,且可以定義多個校驗規(guī)則。
ValidationRule
適用于在ViewModel做數(shù)據(jù)校驗,可以做一些無法在前端頁面做的事情,比如出現(xiàn)異常值是還原為默認值。文章來源:http://www.zghlxwxcb.cn/news/detail-746668.html
所以兩者既可以單獨使用,也可以組合使用,即使使用MVVM模式,依舊能夠優(yōu)雅的做數(shù)據(jù)校驗。文章來源地址http://www.zghlxwxcb.cn/news/detail-746668.html
到了這里,關(guān)于WPF --- TextBox的輸入校驗的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!