Search code examples
c#wpfdatagridcomboboxchildren

Find ComboBox inside DataGrid from specified DataGridRow


I'm trying find a ComboBox inside a DataTemplate in my DataGrid.

To start, I try it:

VisualTreeHelper.GetChildrenCount(dataGridRowInstance);

But it always returns 0.

XAML:

                <DataGrid HorizontalAlignment="Left" Margin="10,54,0,0" VerticalAlignment="Top" Height="231" Width="571" ItemsSource="{Binding}" AutoGenerateColumns="false" x:Name="gridRestore" CellStyle="{StaticResource CellVerticalAlignCenter}">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Created Date" Binding="{Binding Path=CreationTime, ConverterCulture=pt-BR}" Width="120"/>
                        <DataGridTextColumn Header="Length" Binding="{Binding Path=Length}" Width="120"/>
                        <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="200"/>
                        <DataGridTemplateColumn Width="*" Header="Restore To...">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <ComboBox Name="cbx"  Width="120" DropDownOpened="Cbx_OnDropDownOpened" SelectionChanged="Cbx_OnSelectionChanged"></ComboBox>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                    </DataGrid.Columns>
                </DataGrid>

In resume, I want hide the ComboBox according to the test result I do in DataGrid.LoadingRow event.


Solution

  • It's not easy to find an element that is placed into a DataTemplate. You can find an exemple here http://msdn.microsoft.com/en-us/library/bb613579.aspx.

    Assuming you are using the MVVM pattern and that you create a VM per row in your DataGrid, I suggest to add a new property to your VM and bind the combobox visibility to it.