使用 IDataErrorInfo 在验证期间启用禁用保存按钮

发布于 2024-11-17 14:36:56 字数 1990 浏览 3 评论 0原文

如何在使用 IDataErrorInfo 进行验证时禁用/启用按钮?

我正在使用 GalaSoft light Framework 来使用 MVVM。在我的模型类中,我实现了 IDataErrorInfo 来显示错误消息。

public string this[string columnName]
{
    get
    {
        Result = null;
        if (columnName == "FirstName")
        {
            if (String.IsNullOrEmpty(FirstName))
            {
                Result = "Please enter first name";
            }
        }
        else if (columnName == "LastName")
        {
            if (String.IsNullOrEmpty(LastName))
            {
                Result = "Please enter last name";
            }
        }

        else if (columnName == "Address")
        {
            if (String.IsNullOrEmpty(Address))
            {
                Result = "Please enter Address";
            }
        }

        else if (columnName == "City")
        {
            if (String.IsNullOrEmpty(City))
            {
                Result = "Please enter city";
            }
        }

        else if (columnName == "State")
        {
            if (State == "Select")
            {
                Result = "Please select state";
            }
        }

        else if (columnName == "Zip")
        {
            if (String.IsNullOrEmpty(Zip))
            {
                Result = "Please enter zip";

            }
            else if (Zip.Length < 6)
            {
                Result = "Zip's length has to be at least 6 digits!";

            }
            else
            {
                bool zipNumber = Regex.IsMatch(Zip, @"^[0-9]*$");

                if (zipNumber == false)
                {
                    Result = "Please enter only digits in zip";


                }
            }
        }
        else if (columnName == "IsValid")
        {
            Result = true.ToString();
        }

        return Result;

    }
}

屏幕截图:https://i.sstatic.net/kwEI8.jpg

如何禁用/启用保存按钮。请建议?

谢谢

How to disable/enable a button while doing validation using IDataErrorInfo?

I am using MVVM using GalaSoft light Framework. In my Model class I have implemented IDataErrorInfo to display the error messages.

public string this[string columnName]
{
    get
    {
        Result = null;
        if (columnName == "FirstName")
        {
            if (String.IsNullOrEmpty(FirstName))
            {
                Result = "Please enter first name";
            }
        }
        else if (columnName == "LastName")
        {
            if (String.IsNullOrEmpty(LastName))
            {
                Result = "Please enter last name";
            }
        }

        else if (columnName == "Address")
        {
            if (String.IsNullOrEmpty(Address))
            {
                Result = "Please enter Address";
            }
        }

        else if (columnName == "City")
        {
            if (String.IsNullOrEmpty(City))
            {
                Result = "Please enter city";
            }
        }

        else if (columnName == "State")
        {
            if (State == "Select")
            {
                Result = "Please select state";
            }
        }

        else if (columnName == "Zip")
        {
            if (String.IsNullOrEmpty(Zip))
            {
                Result = "Please enter zip";

            }
            else if (Zip.Length < 6)
            {
                Result = "Zip's length has to be at least 6 digits!";

            }
            else
            {
                bool zipNumber = Regex.IsMatch(Zip, @"^[0-9]*$");

                if (zipNumber == false)
                {
                    Result = "Please enter only digits in zip";


                }
            }
        }
        else if (columnName == "IsValid")
        {
            Result = true.ToString();
        }

        return Result;

    }
}

Screenshot: https://i.sstatic.net/kwEI8.jpg

How to disable/enable save button. Kindly suggest?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦在深巷 2024-11-24 14:36:56

Josh Smith 方法是在模型:

static readonly string[] ValidatedProperties =
{
    "Foo",
    "Bar"
};

/// <summary>
/// Returns true if this object has no validation errors.
/// </summary>
public bool IsValid
{
    get
    {
        foreach (string property in ValidatedProperties)
        {

            if (GetValidationError(property) != null) // there is an error
                return false;
        }

        return true;
    }
}

private string GetValidationError(string propertyName)
{
    string error = null;

    switch (propertyName)
    {
        case "Foo":
            error = this.ValidateFoo();
            break;

        case "Bar":
            error = this.ValidateBar();
            break;

        default:
            error = null;
            throw new Exception("Unexpected property being validated on Service");
    }

    return error;
}

ViewModel 然后包含一个 CanSave 属性,用于读取模型上的 IsValid 属性:

/// <summary>
/// Checks if all parameters on the Model are valid and ready to be saved
/// </summary>
protected bool CanSave
{
    get
    {
        return modelOfThisVM.IsValid;
    }
}

最后,如果您使用的是 RelayCommand,您可以设置命令的谓词CanSave 属性,视图将自动启用或禁用该按钮。在 ViewModel 中:

/// <summary>
/// Saves changes Command
/// </summary>
public ICommand SaveCommand
{
    get
    {
        if (_saveCommand == null)
            _saveCommand = new RelayCommand(param => this.SaveChanges(), param => this.CanSave);

        return _saveCommand;
    }
}

在 View 中:

<Button Content="Save" Command="{Binding Path=SaveCommand}"/>

就是这样!

PS:如果你还没有读过约什·史密斯的文章,它将改变你的生活。

The Josh Smith Way of doing this is to create the following methods in the Model:

static readonly string[] ValidatedProperties =
{
    "Foo",
    "Bar"
};

/// <summary>
/// Returns true if this object has no validation errors.
/// </summary>
public bool IsValid
{
    get
    {
        foreach (string property in ValidatedProperties)
        {

            if (GetValidationError(property) != null) // there is an error
                return false;
        }

        return true;
    }
}

private string GetValidationError(string propertyName)
{
    string error = null;

    switch (propertyName)
    {
        case "Foo":
            error = this.ValidateFoo();
            break;

        case "Bar":
            error = this.ValidateBar();
            break;

        default:
            error = null;
            throw new Exception("Unexpected property being validated on Service");
    }

    return error;
}

The ViewModel then contains a CanSave Property that reads the IsValid property on the Model:

/// <summary>
/// Checks if all parameters on the Model are valid and ready to be saved
/// </summary>
protected bool CanSave
{
    get
    {
        return modelOfThisVM.IsValid;
    }
}

Finally, if you are using RelayCommand, you can set the predicate of the command to the CanSave property, and the View will automatically enable or disable the button. In the ViewModel:

/// <summary>
/// Saves changes Command
/// </summary>
public ICommand SaveCommand
{
    get
    {
        if (_saveCommand == null)
            _saveCommand = new RelayCommand(param => this.SaveChanges(), param => this.CanSave);

        return _saveCommand;
    }
}

And in the View:

<Button Content="Save" Command="{Binding Path=SaveCommand}"/>

And that's it!

PS: If you haven't read Josh Smith's article yet, it will change your life.

指尖上的星空 2024-11-24 14:36:56

您可以添加一个布尔属性 CanSave 并将其设置在验证方法的末尾。将按钮中的 IsEnabled 绑定到 IsValid。
像这样的事情:

public bool CanSave
{
  get{ return canSave; }
  set{ canSave = value; RaisePropertyChanged( "CanSave" ); }
}
private bool canSave;

public string this[string columnName]
{
  //....
  CanSave = Result == String.Empty;
}

//xaml
<Button IsEnabled={Binding Path=CanSave}>Save</Button>

you can add add a boolean property CanSave and set it at the end of your valiation method. Bind the IsEnabled from your button to IsValid.
Somthing like this:

public bool CanSave
{
  get{ return canSave; }
  set{ canSave = value; RaisePropertyChanged( "CanSave" ); }
}
private bool canSave;

public string this[string columnName]
{
  //....
  CanSave = Result == String.Empty;
}

//xaml
<Button IsEnabled={Binding Path=CanSave}>Save</Button>
情归归情 2024-11-24 14:36:56

这是我使用 IDataErrorInfo 接口、ValidationErrors Dictionary 和 MVVM-Light 消息传递系统组合的方法。简单明了,工作起来很有魅力:

模型类

public Dictionary<string, string> ValidationErrors = new Dictionary<string, string>();

public string this[string columnName]
{
  get
   {
     // Remove Property error from ValidationErrors prior to any validation
     ValidationErrors.Remove(propertyName);
     //----------------------------------------
     string Result = null;
     if (columnName == "FirstName")
     {
        if (String.IsNullOrEmpty(FirstName))
        {
           // Add Property error to ValidationErrors Dic
           ValidationErrors[propertyName] = Result = "Please enter first name";
           //----------------------------------------
        }
     }
     else if (columnName == "LastName")
     {
        if (String.IsNullOrEmpty(LastName))
        {
          // Add Property error to ValidationErrors Dic
          ValidationErrors[propertyName] = Result = "Please enter last name";
          //----------------------------------------
        }
     }

    // Send MVVM-Light message and receive it in the Code Behind or VM
    Messenger.Default.Send<PersonInfoMsg>(new PersonInfoMsg());
    //----------------------------------------
    return Result;
  }
}

查看隐藏代码

 public partial class PersonInfoView : UserControl
  {
    public PersonInfoView()
    {
        InitializeComponent();
        Messenger.Default.Register<PersonInfoMsg>(this, OnErrorMsg);
    }

    private void OnErrorMsg(PersonInfoMsg)
    {
        // In case of DataGrid validation
        foreach (PersonInfoModel p in GridName.ItemsSource)
        {
            if (p.ValidationErrors.Count == 0)
                SaveBtn.IsEnabled = true;
            else
                SaveBtn.IsEnabled = false;
        }
     }
  }

Here is my way of doing it using a combination of IDataErrorInfo interface, ValidationErrors Dictionary, and MVVM-Light messaging system. Straight forward and works like charm:

Model Class

public Dictionary<string, string> ValidationErrors = new Dictionary<string, string>();

public string this[string columnName]
{
  get
   {
     // Remove Property error from ValidationErrors prior to any validation
     ValidationErrors.Remove(propertyName);
     //----------------------------------------
     string Result = null;
     if (columnName == "FirstName")
     {
        if (String.IsNullOrEmpty(FirstName))
        {
           // Add Property error to ValidationErrors Dic
           ValidationErrors[propertyName] = Result = "Please enter first name";
           //----------------------------------------
        }
     }
     else if (columnName == "LastName")
     {
        if (String.IsNullOrEmpty(LastName))
        {
          // Add Property error to ValidationErrors Dic
          ValidationErrors[propertyName] = Result = "Please enter last name";
          //----------------------------------------
        }
     }

    // Send MVVM-Light message and receive it in the Code Behind or VM
    Messenger.Default.Send<PersonInfoMsg>(new PersonInfoMsg());
    //----------------------------------------
    return Result;
  }
}

View Code Behind

 public partial class PersonInfoView : UserControl
  {
    public PersonInfoView()
    {
        InitializeComponent();
        Messenger.Default.Register<PersonInfoMsg>(this, OnErrorMsg);
    }

    private void OnErrorMsg(PersonInfoMsg)
    {
        // In case of DataGrid validation
        foreach (PersonInfoModel p in GridName.ItemsSource)
        {
            if (p.ValidationErrors.Count == 0)
                SaveBtn.IsEnabled = true;
            else
                SaveBtn.IsEnabled = false;
        }
     }
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文