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

时间:2011-06-30 06:00:08

标签: c# wpf mvvm light

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

我使用的是使用GalaSoft light Framework的MVVM。在我的Model类中,我实现了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

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

由于

2 个答案:

答案 0 :(得分:17)

执行此操作的Josh Smith Way是在模型中创建以下方法:

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属性,View将自动启用或禁用该按钮。在ViewModel中:

/// <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的文章,它将改变你的生活。

答案 1 :(得分:8)

你可以添加一个布尔属性CanSave并在你的valiation方法结束时设置它。将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>