gpt4 book ai didi

wpf - mvvm 中的数据验证

转载 作者:行者123 更新时间:2023-12-02 00:06:39 25 4
gpt4 key购买 nike

我有一个包含多个 ViewModel 的应用程序。某些属性具有 DataAnnotations。

 [Required(ErrorMessage = "Field 'Range' is required.")]
[Range(1, 10, ErrorMessage = "Field 'Range' is out of range.")]
public int Password
{
get
{
return _password;
}
set
{
if (_password != value)
{
_password = value;
RaisePropertyChanged("Password");
}
}
}

如何通过为所有 View 模型实现 IDataErrorInfo 或 INotifyDataErrorInfo 接口(interface)来完成验证?

我使用 This文章,但在属性更改时验证并且不验证必填字段。

最佳答案

这是一个使用 IDataErrorInfo 的简单示例。这应该可以帮助您入门。

XAML:

<Grid>
<Grid.Resources>
<ControlTemplate x:Key="LeftErrorTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding AdornedElement.(Validation.Errors).[0].ErrorContent, ElementName=ErrorAdorner}" Background="Red" Foreground="White" FontWeight="Bold" VerticalAlignment="Center"/>
<AdornedElementPlaceholder x:Name="ErrorAdorner">
<Border BorderBrush="Red" BorderThickness="1" />
</AdornedElementPlaceholder>
</StackPanel>
</ControlTemplate>
</Grid.Resources>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="158,66,0,0" Name="textBlock1" Text="Name" VerticalAlignment="Top" Width="44" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="217,65,0,0" Name="textBox1" VerticalAlignment="Top" Width="120"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
Validation.ErrorTemplate="{StaticResource LeftErrorTemplate}"/>
</Grid>

代码隐藏:

using System;
using System.Windows;
using System.ComponentModel;

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var vm = new ViewModel();

this.DataContext = vm;
}
}

public class ViewModel : ObservableBase, IDataErrorInfo
{
private string _Name;

public string Name
{
get { return _Name; }
set
{
_Name = value;
OnPropertyChanged("Name");
}
}

public string Error
{
get { throw new NotImplementedException(); }
}

public string this[string columnName]
{
get
{
string errorMessage = string.Empty;

switch (columnName)
{
case "Name":
if (string.IsNullOrEmpty(Name))
errorMessage = "Enter name";
else if (Name.Trim() == string.Empty)
errorMessage = "Enter valid name";
break;
}
return errorMessage;
}
}

}

public class ObservableBase : INotifyPropertyChanged
{

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

关于wpf - mvvm 中的数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18041514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com