Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
125
XamDataGrid TemplateField: accessing datacontext from code behind
posted

We are migrating a native WPF DataGrid to a XamDataGrid and we are encountering unexpected behavior.

Our XamDataGrid is bound to an ObservableCollection of ViewModels and includes a TemplateField which encapsulates a user control.   

The user control has an Unloading event in which we need to access the row's DataContext (which we expect to be our ViewModel).  However, when we interrogate the control within the Load event, its DataContext is a string instead of our ViewModel.

The XAML and codebehind is shown below.  Our question is:

How do we get to the row's DataContext (i.e. the DataItem) from the Load Event of a control embedded in a TemplateField?

<igWPF:XamDataGrid Name="dgInfragisticsDataGrid" >

<igDP:XamDataGrid.FieldLayouts>

<igDP:FieldLayout Key="MyViewModel">

<igDP:FieldLayout.Fields>

<igDP:TemplateField AlternateBinding="{Binding Path=MyProperty}">

<igDP:TemplateField.DisplayTemplate>

<DataTemplate>

<TextBlock Text="{igEditors:TemplateEditorValueBinding}" HorizontalAlignment="Right"/>

</DataTemplate>

</igDP:TemplateField.DisplayTemplate>

<igDP:TemplateField.EditTemplate>

<DataTemplate>

<MyApp:MyUserControl

Text="{igEditors:TemplateEditorValueBinding}"

Loaded="MyUserControl_Unloaded"/>

</DataTemplate>

</igDP:TemplateField.EditTemplate>

</igDP:TemplateField>

</igDP:FieldLayout.Fields>

</igDP:FieldLayout>

</igDP:XamDataGrid.FieldLayouts>

</igWPF:XamDataGrid>


private void MyUserControl_Unloaded ( object sender, RoutedEventArgs e )
{
    MyUserControl c = sender as MyUserControl;
  
if (c != null && c.DataContext != null )
  
{
       MyViewModel vm = c.DataContext as MyViewModel;
   
// Do some validation and other stuff
  
}
}

Thank you