在DataGridCell中发生验证错误时,如何继续工作



我想在DataGrid中显示一些值。一列应显示整数值。当用户输入非数字字符时,我想告诉用户,但这个值可能会被持久化。目前,我正在使用DataGridRow的ValidationTemplate。问题是整排。。。在特定单元格中输入整数值之前,完整的DataGrid不再是不可编辑的。我如何才能通知用户他输入了错误的vlaue,但最终允许这样做?

以下是我目前使用的样式:

<Style x:Key="errorRowStyle" TargetType="{x:Type DataGridRow}">
<Setter Property="ValidationErrorTemplate">
<Setter.Value>
<ControlTemplate>
<Grid>
<Ellipse Width="12" Height="12" Fill="Red" Stroke="Black" StrokeThickness="0.5"/>
<TextBlock FontWeight="Bold" Padding="4,0,0,0" Margin="0" VerticalAlignment="Top" Foreground="White" Text="!" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="IsEnabled" Value="True" />
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0]}"/>
</Trigger>
</Style.Triggers>
</Style>

更新2018-01-13:

DataGrid:单元格验证错误时,其他行单元格不可编辑/只读

非常接近我的问题,但它并不能解决输入的(无效)值没有传递到具有无效(字母数字)值的单元格的ObservableCollection绑定(双向)的问题(实际上是字符串属性,但验证器根据整数值进行验证),但有效的整数值是。(正如我所提到的:GUI是宽容的,而不是限制的,它应该给用户一个提示,并可视化输入的值不符合要求,但即使是这个无效的值也应该被接受。)

验证器会是原因吗??

namespace ConfigTool.Tools
{
public class CycleValidationRule : ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
//DataRowView dataRowView = (value as BindingGroup).Items[0] as DataRowView;
//string no = Convert.ToString(dataRowView.Row[0]);
if (int.TryParse(value.ToString(), out int i))
{
return new ValidationResult(true, null);
}
else
{
return new ValidationResult(false,
"Cycle should be an integer value.");
}
}
}
}

这个帮助我找到了解决方案。

我更改了ValidationRule类如下:

public class CycleValidationRule : ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
BindingGroup group = (BindingGroup)value;
StringBuilder error = null;
foreach (var item in group.Items)
{
IDataErrorInfo info = item as IDataErrorInfo;
if (info != null)
{
if (!string.IsNullOrEmpty(info.Error))
{
if (error == null)
{
error = new StringBuilder();
}
error.Append((error.Length != 0 ? ", " : "") + info.Error);
}
}
}
if (error != null)
return new ValidationResult(false, error.ToString());
else
return new ValidationResult(true, "");
}
}

在底层实体类中,以这种方式实现IDataErrorInfo(提取):

string IDataErrorInfo.Error
{
get
{
StringBuilder error = new StringBuilder();
if (!int.TryParse(Cycle.ToString(), out int i))
{
error.Append("Cycle should be an integer value.");
}
return error.ToString();
}
}

在XAML文件中,我添加了

<DataGrid.RowValidationRules>
<local:CycleValidationRule ValidationStep="UpdatedValue" />
</DataGrid.RowValidationRules>

到DataGrid。

最新更新