Search code examples
wpfuser-controlswpfdatagrid

WPF: Need help in adding UserControl in DataGrid using the DataGridTemplateColumn.CellTemplate


I have a WPF UserControl. I want to add that user control in first column of every row in the DataGrid. I have used DataTemplate to achieve this. I add a new row when user hits ENTER key in the last row of the DataGrid. Organisation:OrganisationPicker is the UserControl below.

<DataGridTemplateColumn Width="250" Header="{x:Static resx:Resources.Organisation}" x:Name="OrgPickerColumn" CellStyle="{StaticResource SingleClickEditing}">                                
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <Grid >
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*" Name="column1"></ColumnDefinition>
          <!--<ColumnDefinition Width="0.1*"></ColumnDefinition>-->
        </Grid.ColumnDefinitions>

        <Organisation:OrganisationPicker Width="240"
                                         HorizontalAlignment="Left" Margin="2,2,2,2"
                                         Name="orgPicker"
                                         VerticalAlignment="Top"
                                         Grid.Column="0"
                                         IsValidSearch="{Binding OrganisationError,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=true, NotifyOnValidationError=true,NotifyOnSourceUpdated=True}" 
                                         SelectedOrganisationalUnit="{Binding Path=ReqOrganisationId,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=true, NotifyOnValidationError=true,NotifyOnSourceUpdated=True}"
                                         Foreground="{DynamicResource ContentForeground}" FontFamily="{DynamicResource DefaultFontFamily}" FontSize="{DynamicResource NormalFontSize}">
        </Organisation:OrganisationPicker>                                           
      </Grid>
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

User control gets added but when new row is entered, constructor of the user control is called as many times as number of rows in the grid and obviously I lose the state of the user control instances that are in already present rows.

e.g. If new row thats being added is the 5th row in grid, then constructor is called 5 times!

Why does it happen? How can I prevent it to happen?


Solution

  • The problem was that view model was not written correctly. The collection which is bound to the grid was reinitialized everytime new row is added. So I fixed the view model and it worked.

    Thanks to all for contributing your comments here.

    I am closing this question because solution was too local and it was impossible to identify problem on online forum.