ObservableValidator基礎模型用來驗證數據 和其他框架的基本上一樣
后台代碼
1 using Microsoft.Toolkit.Mvvm.ComponentModel; 2 using System; 3 using System.Collections.Generic; 4 using System.ComponentModel.DataAnnotations; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace MVVMToolkit框架學習 10 { 11 public class NumberAttribute : ValidationAttribute 12 { 13 public NumberAttribute() 14 { 15 } 16 17 public override string FormatErrorMessage(string name) 18 { 19 return base.FormatErrorMessage(name); 20 } 21 22 protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) 23 { 24 if (value == null || string.IsNullOrWhiteSpace(value.ToString())) 25 { 26 return new ValidationResult("內容為空!"); 27 } 28 if (!double.TryParse(value.ToString(), out _)) 29 { 30 return new ValidationResult($"{value}內容不能轉換為數值!"); 31 } 32 33 return ValidationResult.Success; 34 } 35 } 36 37 public class ValidatorVM : ObservableValidator 38 { 39 private string _name; 40 41 private string _weight; 42 43 [Required(AllowEmptyStrings = false, ErrorMessage = "名字不可為空")] 44 [MaxLength(6, ErrorMessage = "長度不能大於6")] 45 public string Name 46 { 47 get => _name; 48 49 //需要驗證屬性就使用重載方法 50 set => SetProperty(ref _name, value, true); 51 } 52 53 [Number] 54 public string Weight 55 { 56 get => _weight; 57 58 //驗證自定義屬性 59 set => SetProperty(ref _weight, value, true); 60 } 61 62 public ValidatorVM() 63 { 64 } 65 } 66 }
前台代碼
1 <Window 2 x:Class="MVVMToolkit框架學習.ValidateView" 3 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 4 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 5 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 6 xmlns:local="clr-namespace:MVVMToolkit框架學習" 7 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 8 Title="ValidateView" 9 Width="800" 10 Height="450" 11 d:DataContext="{d:DesignInstance Type={x:Type local:ValidatorVM}}" 12 FontSize="30" 13 mc:Ignorable="d"> 14 <Window.DataContext> 15 <local:ValidatorVM /> 16 </Window.DataContext> 17 <Window.Resources> 18 <Style TargetType="TextBox"> 19 <Setter Property="Validation.ErrorTemplate"> 20 <Setter.Value> 21 <ControlTemplate> 22 <StackPanel> 23 <AdornedElementPlaceholder /> 24 <ItemsControl ItemsSource="{Binding}"> 25 <ItemsControl.ItemTemplate> 26 <DataTemplate> 27 <TextBlock 28 Foreground="Red" 29 Text="{Binding ErrorContent}" /> 30 </DataTemplate> 31 </ItemsControl.ItemTemplate> 32 </ItemsControl> 33 </StackPanel> 34 </ControlTemplate> 35 </Setter.Value> 36 </Setter> 37 </Style> 38 </Window.Resources> 39 <Grid> 40 <StackPanel 41 MinWidth="200" 42 HorizontalAlignment="Center" 43 VerticalAlignment="Center" 44 Orientation="Vertical"> 45 <TextBlock Text="Name" /> 46 <TextBox 47 Margin="0,0,0,30" 48 Text="{Binding Name}" /> 49 50 <TextBlock Text="Weight" /> 51 <TextBox 52 Margin="0,0,0,30" 53 Text="{Binding Weight}" /> 54 </StackPanel> 55 </Grid> 56 </Window>