Reputation: 25
Think my binding is off somewhere, I would like to show the validation error as a tool tip in the datagrid. I would appreciate someone making a suggestion on how to accomplish this or point out my mistake
My Simple Test Model:
public class TimeSheets
{
public int Id { get; set; }
public double MondayTime { get; set; }
}
The View:
public class TimeSheets
{
public int Id { get; set; }
public double MondayTime { get; set; }
}
ViewModel:
public class DataGridViewModel : Screen, IDataErrorInfo
{
private BindableCollection<TimeSheets> _times = new BindableCollection<TimeSheets>();
private readonly DataGridViewModelValidator _dgVal;
public BindableCollection<TimeSheets> Times
{
get { return _times; }
set { _times = value;
NotifyOfPropertyChange(() => Times);
}
}
public DataGridViewModel()
{
Times.Add(new TimeSheets { Id = 1, MondayTime = 3.5 });
_dgVal = new DataGridViewModelValidator();
}
public string this[string columnName]
{
get
{
var firstOrDefault =_dgVal.Validate(this).Errors.FirstOrDefault(lol => lol.PropertyName == columnName);
if (firstOrDefault != null)
return _dgVal != null ? firstOrDefault.ErrorMessage : "";
return "";
}
}
public string Error
{
get
{
if (_dgVal != null)
{
FluentValidation.Results.ValidationResult results = _dgVal.Validate(this);
if (results != null && results.Errors.Any())
{
string errors = string.Join(Environment.NewLine, results.Errors.Select(x => x.ErrorMessage).ToArray());
return errors;
}
}
return string.Empty;
}
}
}
Class Model Validation:
public class TimeSheetValidator:AbstractValidator<TimeSheets>
{
public TimeSheetValidator()
{
RuleFor(x => x.Id)
.Empty()
.WithMessage("Empty ID");
RuleFor(x => x.MondayTime)
.Empty()
.WithMessage("Time Empty");
RuleFor(x => x.MondayTime)
.Equal(3.5)
.WithMessage("Valildation");
}
}
ListValidation from the Viewmodel:
enter cod public class DataGridViewModelValidator : AbstractValidator<DataGridViewModel>
{
public DataGridViewModelValidator()
{
RuleForEach(x => x.Times).SetValidator(new TimeSheetValidator());
}
}
Upvotes: 0
Views: 164
Reputation: 61
If your XAML looks something like,
<DataGrid ToolTip="{Binding Error}">
......
</DataGrid>
you will the Errors property value when initializing the WPF components. If you want to update this you have to call an OnpropertyChanged
delegate for Error
to triggern a binding refresh. This should do it as you already provide the data in Error.Get
.
Upvotes: 1