WPF validation (BindingGroup).item[0] return null
本文关键字:return null item validation BindingGroup WPF | 更新日期: 2023-09-27 18:30:54
我正在尝试根据 MSDN 示例 http://msdn.microsoft.com/en-us/library/ee622975(v=vs.110)为我的数据网格进行一些验证.aspx ,
XAML 代码
<DataGrid x:Name="grdQuoteDetail" Height="319" VerticalAlignment="Top" DockPanel.Dock="Top" Margin="0,10,0,0" RowEditEnding="grdQuoteDetailSave" CellEditEnding="grdQuoteDetail_CellEditEnding" AutoGenerateColumns="False">
<DataGrid.RowValidationRules>
<local:CourseValidationRule ValidationStep="UpdatedValue"/>
</DataGrid.RowValidationRules>
<DataGrid.Columns>
<DataGridTextColumn Header="No" Binding="{Binding No , ValidatesOnExceptions=True}" Width="50" />
<DataGridTextColumn Header="Description" Binding="{Binding Description}" Width="*" />
<DataGridTextColumn Header="Total" Binding="{Binding Total}" Width="120" />
</DataGrid.Columns>
</DataGrid>
不同的是我正在使用一个类来生成数据表并将网格的项源设置为它。
CS 代码
private void genTable()
{
dtQuoteDetail.Columns.Add(new DataColumn("No", Type.GetType("System.Int32")));
dtQuoteDetail.Columns.Add(new DataColumn("Description", Type.GetType("System.String")));
dtQuoteDetail.Columns.Add(new DataColumn("Total", Type.GetType("System.Double")));
DataRow dr = dtQuoteDetail.NewRow();
dr["No"] = 1;
dr["Description"] = "";
dr["Total"] = 0;
dtQuoteDetail.Rows.Add(dr);
grdQuoteDetail.ItemsSource = dtQuoteDetail.DefaultView;
}
验证码
public class CourseValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
tblTesting qt = (value as BindingGroup).Items[0] as tblTesting ; //Return Null
if (qt.No > 10)
{
return new ValidationResult(false, "This Numbe cannot greater than 10");
}
else
{
return ValidationResult.ValidResult;
}
}
}
用于 tblTesting 的类文件
public class tblTesting
{
public int No {get;set;}
public string Description {get;set;}
public double Total {get;set;}
}
我正在为空
.qt
我不知道为什么,任何指导将不胜感激。
因为(value as BindingGroup).Items[0]
的类型是'DataRowView',所以它与你的tblTesting
类无关。
您可以获取与 NO
属性对应的第一个单元格的值。
var dataRowView = (value as BindingGroup).Items[0] as DataRowView;
int no = Convert.ToInt32(dataRowView.Row[0]);
if (no > 10)
//do the rest...