Search code examples
c#xamlwindows-store-appswindows-8.1visualtreehelper

Finding Canvas within the visual tree


I have a FlipView controll which in its data template got a scrollviewer, which then got a canvas with the controls. My problem is that I need to access the canvas inside the eventhandler for the FlipView.SelectionChanged event.

The Xaml for the FlipView looks like this.

<FlipView Grid.Row="1"
   d:DataContext="{d:DesignInstance model:PageContent}"
   SelectionChanged="FlipView_SelectionChanged"
   ItemsSource="{Binding TiffPages}"
   x:Name="flBillImage">
   <FlipView.ItemTemplate>
       <DataTemplate>
          <ScrollViewer x:Name="scrollBill" 
               VerticalScrollBarVisibility="Auto" 
               HorizontalScrollBarVisibility="Auto" 
               ZoomMode="Enabled"
               DataContextChanged="scrollBill_DataContextChanged">
                   <Canvas x:Name="cvBill"
                       DataContextChanged="cvBill_DataContextChanged"
                       Loaded="cvBill_Loaded"
                       HorizontalAlignment="Left"
                       VerticalAlignment="Top"
                       FlowDirection="LeftToRight" >

                   <Image x:Name="imgBill"            
                       Loaded="imgBill_Loaded"
                       DataContextChanged="imgBill_DataContextChanged"
                       Canvas.ZIndex="0"
                       Source="{Binding BillImage}"
                       Visibility="{Binding IsFrameExtracted, Converter={StaticResource     BooleanToVisibilityConverter}}" />
               </Canvas>
           </ScrollViewer>
       </DataTemplate>
   </FlipView.ItemTemplate>
</FlipView>

And the C# code for parsing the visual tree looks like this:

 public static List<Control> AllChildren(DependencyObject parent)
    {
        var _List = new List<Control>();
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var _Child = VisualTreeHelper.GetChild(parent, i);
            if (_Child is Control)
            {
                _List.Add(_Child as Control);
            }
            _List.AddRange(AllChildren(_Child));
        }
        return _List;
    }

Which is used like:

var ctrls = AllChildren(flBillImage);

Checking the returned list I can find the ScrollViewer but I can't find the Canvas. I have also tried to supply the scrollviewer returned as argument to the AllChildren function but I still can't seem to find the Canvas control.

Am I doing this all wrong?


Solution

  • I faced a similar type of problem quite some time ago. This solution was used to access the child elements of a tree in the code-behind. Much straight-forward.

    Hope this helps you.