WPF DataGrid多行验证问题:绑定Waypoint至行验证模板
嘿,我刚好折腾过类似的WPF行验证场景,给你捋清楚怎么把Waypoint对象绑定到DataGrid的行验证模板里:
实现WPF DataGrid行验证模板绑定Waypoint对象
核心问题是让RowValidationTemplate的DataContext指向行对应的Waypoint实例(而不是默认的BindingGroup)。因为DataGridRow的DataContext就是你的Waypoint对象,我们可以通过RelativeSource来精准获取它。
1. 定义RowValidationTemplate并绑定到Waypoint
在你的DataGrid XAML中,添加行验证模板,通过RelativeSource找到DataGridRow,再绑定它的DataContext(也就是Waypoint)的错误信息:
<DataGrid ItemsSource="{Binding Waypoints}" AutoGenerateColumns="False"> <!-- 你的列定义,绑定到DataItem的Value属性 --> <DataGrid.Columns> <DataGridTextColumn Header="数据项1" Binding="{Binding DataItem1.Value, ValidatesOnDataErrors=True}" /> <DataGridTextColumn Header="数据项2" Binding="{Binding DataItem2.Value, ValidatesOnDataErrors=True}" /> <!-- 其他列... --> </DataGrid.Columns> <!-- 行验证模板 --> <DataGrid.RowValidationTemplate> <ControlTemplate> <Grid Margin="0,0,10,0" VerticalAlignment="Center"> <Ellipse Width="12" Height="12" Fill="Red" /> <TextBlock Text="!" Foreground="White" FontWeight="Bold" HorizontalAlignment="Center" <!-- 绑定到Waypoint的Error属性,显示行级错误提示 --> ToolTip="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=DataContext.Error}" /> </Grid> </ControlTemplate> </DataGrid.RowValidationTemplate> </DataGrid>
2. 完善Waypoint的IDataErrorInfo实现
要让行级验证生效,Waypoint的IDataErrorInfo需要正确返回行级错误——如果是汇总子DataItem的错误,就在Error属性里遍历所有子项收集信息:
public class Waypoint : IDataErrorInfo { public DataItem DataItem1 { get; set; } = new DataItem(); public DataItem DataItem2 { get; set; } = new DataItem(); // 其他DataItem属性... public string Error { get { var errorList = new List<string>(); // 收集所有子DataItem的错误 if (!string.IsNullOrEmpty(DataItem1.Error)) errorList.Add($"数据项1: {DataItem1.Error}"); if (!string.IsNullOrEmpty(DataItem2.Error)) errorList.Add($"数据项2: {DataItem2.Error}"); // 加上Waypoint自身的验证错误(如果有) // if (!IsWaypointValid()) errorList.Add("Waypoint自身验证失败"); return string.Join(Environment.NewLine, errorList); } } public string this[string columnName] { get { // 这里处理Waypoint自身属性的验证逻辑(如果需要) return string.Empty; } } }
3. 验证生效的关键细节
- 确保列绑定的
ValidatesOnDataErrors=True,这样子DataItem的错误会被触发,Waypoint的Error属性也能正确收集到这些信息。 - 不需要额外配置BindingGroup,因为我们直接通过DataGridRow的DataContext绑定Waypoint,绕过了默认的BindingGroup验证上下文。
内容的提问来源于stack exchange,提问作者Stephen Dye
相关产品推荐
相关产品推荐

