gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:31:23 25 4
gpt4 key购买 nike

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

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

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

谢谢

最佳答案

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 将自动启用或禁用该按钮。在 View 模型中:

/// <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:如果你还没有读过 Josh Smith 的文章,它会改变你的生活。

关于c# - 使用 IDataErrorInfo 在验证期间启用禁用保存按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6530529/

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