9

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

我正在使用MVVMGalaSoft 灯光框架。在我的模型类中,我实现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;

    }
}

截图:http: //i.stack.imgur.com/kwEI8.jpg

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

谢谢

4

3 回答 3

18

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 包含一个CanSaveProperty,它读取IsValid Model 上的属性:

/// <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属性,视图会自动启用或禁用按钮。在视图模型中:

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

        return _saveCommand;
    }
}

在视图中:

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

就是这样!

PS:如果你还没有读过 Josh Smith 的文章,它将改变你的生活。

于 2011-06-30T07:51:08.103 回答
8

您可以添加一个布尔属性 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>
于 2011-06-30T07:03:05.373 回答
1

这是我结合使用 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;
        }
     }
  }
于 2017-08-11T20:11:24.383 回答