You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Prism 6.3 WPF(C#)应用中实现用户输入验证及表单校验?

Hey there! I’ve been right where you are—working with Prism 6.3 for WPF and scratching my head over validation since Brian’s tutorials don’t cover it. Let’s walk through exactly how to set this up, step by step.

1. Implementing Validation Rules in Prism 6.3

Prism supports a couple of solid approaches for validation, depending on whether you prefer classic WPF patterns or more modern data annotations.

Option 1: Use IDataErrorInfo (Classic WPF Approach)

Prism’s ViewModelBase already implements the IDataErrorInfo interface, so you can just override the necessary members to add your rules. Here’s a concrete example with a user form:

public class UserViewModel : ViewModelBase
{
    private string _name;
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    private string _email;
    public string Email
    {
        get => _email;
        set => SetProperty(ref _email, value);
    }

    // Override the indexer to return errors for specific properties
    public override string this[string columnName]
    {
        get
        {
            string error = null;
            switch (columnName)
            {
                case nameof(Name):
                    if (string.IsNullOrWhiteSpace(Name))
                        error = "Name is required.";
                    else if (Name.Length < 2)
                        error = "Name must be at least 2 characters long.";
                    break;
                case nameof(Email):
                    if (string.IsNullOrWhiteSpace(Email))
                        error = "Email is required.";
                    else if (!new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(Email))
                        error = "Invalid email format.";
                    break;
            }
            return error;
        }
    }
}

To hook this up in your XAML, add ValidatesOnDataErrors=True to your bindings so WPF knows to use the validation logic:

<StackPanel>
    <TextBox Text="{Binding Name, ValidatesOnDataErrors=True}" Margin="5" />
    <TextBox Text="{Binding Email, ValidatesOnDataErrors=True}" Margin="5" />
</StackPanel>

Option 2: Use Data Annotations (Prism's Preferred Modern Approach)

Prism 6.3 works seamlessly with .NET data annotations, leveraging the INotifyDataErrorInfo interface (which is more flexible than IDataErrorInfo). Again, ViewModelBase handles most of the heavy lifting here—just add attributes to your properties:

using System.ComponentModel.DataAnnotations;

public class UserViewModel : ViewModelBase
{
    private string _name;
    [Required(ErrorMessage = "Name is required.")]
    [MinLength(2, ErrorMessage = "Name must be at least 2 characters long.")]
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    private string _email;
    [Required(ErrorMessage = "Email is required.")]
    [EmailAddress(ErrorMessage = "Invalid email format.")]
    public string Email
    {
        get => _email;
        set => SetProperty(ref _email, value);
    }
}

For this approach, update your XAML bindings to use ValidatesOnNotifyDataErrors=True:

<StackPanel>
    <TextBox Text="{Binding Name, ValidatesOnNotifyDataErrors=True}" Margin="5" />
    <TextBox Text="{Binding Email, ValidatesOnNotifyDataErrors=True}" Margin="5" />
</StackPanel>

Prism automatically triggers validation whenever you call SetProperty, so you don’t have to manually fire validation events—nice!

2. Checking Form Validity Before Saving

Now that your validation rules are in place, you need to make sure the form is fully valid before sending data to the database. Prism’s ViewModelBase gives you built-in tools for this.

Quick Check with HasErrors

The simplest way is to use the HasErrors property, which returns true if any property has validation errors:

private DelegateCommand _saveCommand;
public DelegateCommand SaveCommand => 
    _saveCommand ?? (_saveCommand = new DelegateCommand(SaveCommandExecute));

private void SaveCommandExecute()
{
    if (!HasErrors)
    {
        // Your database submission logic goes here
        MessageBox.Show("Data saved successfully!");
    }
    else
    {
        // Alert the user to fix errors
        MessageBox.Show("Please correct all validation errors before saving.");
    }
}

Force Full Validation (For Unedited Fields)

Sometimes users might skip editing a field (like leaving a required TextBox untouched), which means validation never triggers for that property. To cover this, add a method to validate all properties manually:

private void ValidateAllProperties()
{
    var properties = GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
    foreach (var property in properties)
    {
        // Use Prism's built-in ValidateProperty method to check each property
        ValidateProperty(property.Name, GetValue(property));
    }
}

Then update your save command to run this first:

private void SaveCommandExecute()
{
    ValidateAllProperties(); // Force check all fields
    if (!HasErrors)
    {
        // Save to database
    }
    else
    {
        MessageBox.Show("Please fix all errors before saving.");
    }
}
3. Bonus: Display All Errors in a List

If you want to show all validation errors in a single place (instead of just per-field), add a property to collect all errors:

public IEnumerable<string> AllValidationErrors
{
    get
    {
        var errors = new List<string>();
        var properties = GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        
        foreach (var property in properties)
        {
            var propertyErrors = GetErrors(property.Name).Cast<string>();
            errors.AddRange(propertyErrors);
        }
        
        return errors;
    }
}

Then bind it to an ItemsControl in your XAML:

<ItemsControl ItemsSource="{Binding AllValidationErrors}" 
              Foreground="Red" 
              Margin="5" />

内容的提问来源于stack exchange,提问作者Junior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:57:14