WPF - FrameworkElement - Enumerate all decendents?

你。 提交于 2019-12-24 01:58:13

问题


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.



来源:https://stackoverflow.com/questions/2285196/wpf-frameworkelement-enumerate-all-decendents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!