views:

305

answers:

1

I have a Silverlight 3 tools library with a custom DataGrid user control. This grid has no direct access to the WCF RIA Services entity types so I'm using reflection to add a new item when the user clicks on the grid when it's empty:

private void InsertEmptyRecord()
{
    if (this._dataGrid.ItemsSource == null)
        return;

    Type[] typeParameters = this._dataGrid.ItemsSource.GetType().GetGenericArguments();
    if (typeParameters.Count() > 0)
    {
        Type itemType = typeParameters[0];
        object newItem = System.Activator.CreateInstance(itemType);

        Type sourceType = typeof(System.Windows.Ria.EntityCollection<>);
        Type genericType = sourceType.MakeGenericType(itemType);
        System.Reflection.MethodInfo addMethod = genericType.GetMethod("Add");
        addMethod.Invoke(this._dataGrid.ItemsSource, new object[] { newItem });

        // == Validate data here ==
    }
}

This works, but I need it to also validate after the new item is added. There are two ways I can see to do this:

  1. Force the user to enter edit mode for the first cell of the new row in the grid. (This would force validation if they click anywhere else on the page.)
  2. Force validations to run immediately when the new row is added (or when the grid looses focus.)

I haven't been able to get either of these to work. Tried this but it only selects the row, doesn't force the validations to run:

this._dataGrid.SelectedItem = newItem;
System.ComponentModel.IEditableObject editableItem = newItem as System.ComponentModel.IEditableObject;
if (editableItem != null)
    editableItem.BeginEdit();

Any suggestions?

A: 

Just got this working thanks to some help from this question.

I added the following to the "== Validate data here ==" section in the code from above:

DataGridRow newRow = this._dataGrid.ChildrenOfType<DataGridRow>().FirstOrDefault();
if (newRow != null)
{
    newRow.Loaded += (sender, e) =>
    {
        this._dataGrid.CurrentItem = newItem;
        this._dataGrid.BeginEdit();
    };
}

This forces the first cell to immediately go into edit mode.

Nick Gotch