Если запись недоступна, я хочу добавить TextBlock
в сетку данных под заголовком, показывая сообщение «Запись не найдена. Требуемый валидатор срабатывает правильно, но точка останова внутри метода валидации моего пользовательского валидатора никогда не срабатывает. Я не понимаю, почему это так, поскольку я думаю, что очень внимательно следил за примером MS: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute (v = vs .95) .aspx
Вот код для модели представления:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using GalaSoft.MvvmLight.Command;
namespace MyProject
{
// custom validation class
public class StartsCapitalValidator
{
public static ValidationResult IsValid(string value)
{
// this code never gets hit
if (value.Length > 0)
{
var valid = (value[0].ToString() == value[0].ToString().ToUpper());
if (!valid)
return new ValidationResult("Name must start with capital letter");
}
return ValidationResult.Success;
}
}
// my view model
public class ValidationTestViewModel : ViewModelBase
{
// the property to be validated
string _name;
[Required]
[CustomValidation(typeof(StartsCapitalValidator), "IsValid")]
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value, () => Name); }
}
string _result;
public string Result
{
get { return _result; }
private set { SetProperty(ref _result, value, () => Result); }
}
public RelayCommand SubmitCommand { get; private set; }
public ValidationTestViewModel()
{
SubmitCommand = new RelayCommand(Submit);
}
void Submit()
{
// perform validation when the user clicks the Submit button
var errors = new List();
if (!Validator.TryValidateObject(this, new ValidationContext(this, null, null), errors))
{
// we only ever get here from the Required validation, never from the CustomValidator
Result = String.Format("{0} error(s):\n{1}",
errors.Count,
String.Join("\n", errors.Select(e => e.ErrorMessage)));
}
else
{
Result = "Valid";
}
}
}
}
Вот представление: