我的问题是 DataGrid 中验证错误的行为。它针对我的模型对象的属性进行验证并显示正确的消息,但是每当我选择不同的行时,验证以及原始值都会消失。
在下面的示例 .gif 中,我删除了名称(退格键),按 Enter 键(获取验证消息),然后单击另一行。 Whenever the selected row changes I would expect either a) the validation error to remain OR b) the original value to return, but the row stays blank and the validation error is gone until I double click the row.一旦我双击,原始值就会返回。
我希望验证错误持续存在,但我会在这一点上采取任何一个。
这是数据网格文本 block 样式:
<Style x:Key="datagridElemStyle" TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Yellow" />
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
这是实际的 DataGridTextColumn:
<DataGridTextColumn Header="NAME"
Width="300"
Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=LostFocus,
ValidatesOnExceptions=True}"
ElementStyle="{StaticResource datagridElemStyle}"
CanUserReorder="False" />
这是我的 ViewModel 包装器对象(省略了不相关的部分):
public class PointVM : INotifyPropertyChanged
{
public Point DataContext { get; set; }
public string Name
{
get { return DataContext.Name; }
set
{
if (value != DataContext.Name)
{
DataContext.Name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
}
最后,这是我的模型(省略了无关部分):
public abstract class Point
{
private string _name;
public string Name
{
get { return _name; }
set
{
string trimmedVal = value.Trim();
#region Validation
if (string.IsNullOrEmpty(trimmedVal))
throw new Exception("Name cannot be empty.");
if (Regex.IsMatch(trimmedVal, @"[^A-Za-z0-9\-_ ]$"))
throw new Exception("Invalid character in name.");
if (trimmedVal.Length > 64)
throw new Exception("Name is too long.");
if ((from p in PointList
where p.Name.Equals(trimmedVal, StringComparison.OrdinalIgnoreCase)
select p).Count() > 0)
throw new Exception("Name is already used.");
#endregion
_name = trimmedVal;
}
}
谢谢你的时间。
最佳答案
DataGrid 验证可能非常烦人。当一个 DataGridTextColumn
开始编辑时,绑定(bind)的实际值被恢复,这就是您进入编辑模式时看到恢复的原因。
您基本上需要通过处理 BeginningEdit
来停止该调用。 DataGrid 的事件。
<DataGrid AutoGenerateColumns="False" BeginningEdit="dg_BeginningEdit">
代码隐藏
private void dg_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
e.EditingEventArgs.Handled = true;
}
仅供引用:您在
LostFocus
上的绑定(bind)更新.如果您在 PropertyChanged
上更新,此解决方案可能无法正常工作将来,因为它会改变操作顺序。
关于c# - WPF MVVM Datagrid 单元格验证错误行为问题 : Why is my value being removed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49826073/