WPF - FrameworkElement - Enumerate all decendents?

2019-07-20 11:12发布

问题:

I have a FrameworkElement (really a ToggleButton) that has inside its content a Popup.

I access it like this:

ToggleButton button = (ToggleButton)sender;
Popup popup = (Popup)button.FindName("popSelectIteration");

Usually this works fine. But sometimes popup is null.

I am trying to find a way to debug this. Is there a way enumerate all the "things" that FindName could find?


As background, here is how my popup is defined in the ToggleButton:

<ToggleButton Grid.Column="1" HorizontalAlignment="Right" Margin="0,2,0,2" Checked="btnFindIterationChecked">
 <Grid>
  <Popup PlacementTarget="{Binding ElementName=chkIteration}"  Name="popSelectIteration" Closed="popSelectIteration_Closed"
     AllowsTransparency="True" StaysOpen="False" PopupAnimation="Fade">
      <Border BorderBrush="#FF000000" Background="LightBlue" BorderThickness="1,1,1,1" CornerRadius="8,8,8,8" Padding="5">
        <Grid>
          <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="300"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
          </Grid.RowDefinitions>
          <TextBlock Foreground="Black" >Select Destination:</TextBlock>
          <ScrollViewer Grid.Row="1" >
            <TreeView ItemsSource="{Binding IterationTree}" SelectedItemChanged="TreeView_SelectedItemChanged">
              <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Children}">
                  <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding PathEnd}" />
                  </StackPanel>
                </HierarchicalDataTemplate>
              </TreeView.ItemTemplate>
            </TreeView>
          </ScrollViewer>
          <Button Grid.Row="2" Background="LightBlue" Content="Clear Selection" Click="btnClear_Click"/>
        </Grid>
      </Border>
    </Popup>
  </Grid>
</ToggleButton>

回答1:

Try Snoop. It is a great WPF debugging utility for everything that concerns the visual tree.

Edit: Your specific problem seems to be a timing issue though. I guess that the tree is not completely constructed yet and you try to access a child element although it is not created. Wait until the topmost element receives a "Loaded" event.