WPF View页面数据验证,多个页面都需要验证需要提取到View Model的父类里完成,请给出代码示例
时间: 2024-03-08 08:46:24 浏览: 22
假设我们有两个需要进行数据验证的 View 页面,分别为 `Page1.xaml` 和 `Page2.xaml`,我们可以先在 View Model 的父类里定义需要验证的属性和方法,然后在每个 View Model 里继承这个父类,并在构造函数里设置对应的验证规则。
以下是代码示例:
```csharp
// 父类 BaseViewModel.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class BaseViewModel : INotifyPropertyChanged, IDataErrorInfo
{
// 需要验证的属性
protected string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged();
}
}
}
// IDataErrorInfo 接口实现
public string this[string columnName]
{
get
{
string error = null;
switch (columnName)
{
case "Name":
// 设置 Name 属性的验证规则
if (string.IsNullOrEmpty(Name))
{
error = "Name is required.";
}
break;
}
return error;
}
}
public string Error
{
get { return null; }
}
// INotifyPropertyChanged 接口实现
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
// 子类 Page1ViewModel.cs
public class Page1ViewModel : BaseViewModel
{
public Page1ViewModel()
{
// 设置 Page1 的验证规则
Name = "";
}
}
// 子类 Page2ViewModel.cs
public class Page2ViewModel : BaseViewModel
{
public Page2ViewModel()
{
// 设置 Page2 的验证规则
Name = "";
}
}
// Page1.xaml.cs
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
// 设置 DataContext
DataContext = new Page1ViewModel();
}
}
// Page2.xaml.cs
public partial class Page2 : Page
{
public Page2()
{
InitializeComponent();
// 设置 DataContext
DataContext = new Page2ViewModel();
}
}
```
在父类 `BaseViewModel` 中,我们定义了需要验证的属性 `Name`,并实现了 `IDataErrorInfo` 接口和 `INotifyPropertyChanged` 接口。在子类 `Page1ViewModel` 和 `Page2ViewModel` 中,我们继承了父类,并在构造函数里设置了对应的验证规则。
在 View 层中,我们分别创建了 `Page1.xaml` 和 `Page2.xaml`,并在构造函数里设置了对应的 View Model,并将其设置为 DataContext。这样,当我们在 UI 中修改 `Name` 属性的值时,就会触发数据验证,并且错误信息会显示在 UI 上。