我正在尝试为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>
不同的是我正在使用类生成数据表并将网格的itemsource设置为它。
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;}
}
我正在获取NUll
QT
我不知道为什么,任何指导都会受到赞赏。
答案 0 :(得分:1)
因为(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...