【发布时间】:2012-10-30 06:11:57
【问题描述】:
当 DataGrid 没有行时,我想在 DataGrid 周围放置一个红色边框(我正在绑定到 ItemsSource)。
所以我一直在关注这个 WPF 验证指南:
http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation
不管怎样,在Text = ""时让一个文本框出现这样的错误很简单:
甚至自定义错误:
我尝试调试并且绑定在我的 ItemsSource 中的 ValidationRules 从未被调用。
<DataGrid ...>
<DataGrid.ItemsSource>
<Binding Path="Lines" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<DataGridValidationRule
MiniumRows="1"
MaximumRows="100"
ErrorMessage="must have between 1 and 100 rows">
</DataGridValidationRule>
</Binding.ValidationRules>
</Binding>
</DataGrid.ItemsSource>
</DataGrid>
然后 DataGridValidtionRule 类看起来像这样:
public class public class StringRangeValidationRule : ValidationRule
{
private int _minimumRows = -1;
private int _maximumRows = -1;
private string _errorMessage;
public int MinimumRows
{
get { return _minimumRows ; }
set { _minimumRows = value; }
}
public int MaximumRows
{
get { return _maximumLength; }
set { _maximumLength = value; }
}
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
public override ValidationResult Validate(object value,
CultureInfo cultureInfo)
{
ValidationResult result = new ValidationResult(true, null);
ObservableCollection<Lines> lines = (ObservableCollection<Lines>) value;
if (lines.Count < this.MinimumRows||
(this.MaximumRows> 0 &&
lines.Count > this.MaximumRows))
{
result = new ValidationResult(false, this.ErrorMessage);
}
return result;
}
还有“线条”类
public class Line
{
public Line(string f, string b)
{
foo = f;
bar = b;
}
public string Foo {get; set;}
public string Bar {get; set;}
}
编辑:
事实证明,我的数据网格的“删除行”按钮是从 ObservableCollection 中删除的,但不是通过实际的 DataGrid(它在 ViewModel 上删除)...由于某种原因,这会阻止验证调用被调用。
又是视图:
<DataGrid Name="mygrid">
<DataGrid.ItemsSource>
<Binding Path="Lines" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<DataGridValidationRule
MiniumRows="1"
MaximumRows="100"
ErrorMessage="must have between 1 and 100 rows">
</DataGridValidationRule>
</Binding.ValidationRules>
</Binding>
</DataGrid.ItemsSource>
</DataGrid>
所以如果我在 ViewModel 中有:
void delete(Line l)
{
Lines.Remove(l); //if you delete everything (grid empty) there won't be any error shown.
}
错误边框和图标不会显示在数据网格周围。
但是,如果我改为放置一个直接更改 ItemsSource 的事件,如下所示:
void delete(Line l)
{
Lines.Remove(l);
myView.mygrid.ItemsSource = Lines; // this magically fixes everything... even though it was already bound to Lines... though i hate to directly access the View from within the ViewModel.
}
我不知道究竟是为什么......但这解决了它。 关于如何将视图与 VM 分开的任何想法?我真的不喜欢这个修复。
【问题讨论】:
标签: wpf validation datagrid