WPF validation (BindingGroup).item[0] return null

761 views Asked by At

I am trying to work out some validation for my datagrid base on MSDN example http://msdn.microsoft.com/en-us/library/ee622975(v=vs.110).aspx ,

XAML Code

 <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>

The different is I am using a class to generate datatable and set the itemsource of the grid to it .

CS code

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;  

}

Validation Code

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;
        }

    }
}

Class File for tblTesting

 public class tblTesting 
 { 
        public int No {get;set;}
        public string Description {get;set;}
        public double Total {get;set;}
 }

I am getting NUll for

qt

I have no idea why , any guidance will be appreciate.

1

There are 1 answers

0
kennyzx On BEST ANSWER

Because (value as BindingGroup).Items[0] is of the type 'DataRowView', it has nothing to do with your tblTesting class.

You can get the value of the first cell that corresponds to the NO property.

var dataRowView = (value as BindingGroup).Items[0] as DataRowView;
int no = Convert.ToInt32(dataRowView.Row[0]);

if (no > 10)
//do the rest...