Select ImageBrush using VisualTreeHelper

74 views Asked by At

I am trying to select ImageBrush items from a LongListSelector. As the ImageBrushes are inside a DataTemplate, I am selecting them using VisualTreeHelper.

My sample xaml code:

<phone:LongListSelector Grid.Row="0" Name="AllPhotosListBox"
                                SelectionChanged="AllPhotosListBox_SelectionChanged"
                                ItemsSource="{Binding PhotoItems}" 
                                LayoutMode="Grid" GridCellSize="112, 112">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <Border Margin="24,12,-12,0" Grid.Row="2" BorderThickness="1" BorderBrush="Gray" >
                <Grid toolkit:TiltEffect.IsTiltEnabled="True">
                    <Grid.Background>
                        <ImageBrush ImageSource="{Binding ImageUrlLow}" Stretch="UniformToFill" />
                    </Grid.Background>
                </Grid>
            </Border>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

My sample c# code for selecting ImageBrushes is:

for (int i = 0; i < AllPhotosListBox.ItemsSource.Count; i++)
{
    AllPhotosListBox.UpdateLayout();
    AllPhotosListBox.ScrollTo(AllPhotosListBox.ItemsSource[i]);

    LongListSelector longListBoxItem = AllPhotosListBox as LongListSelector;
    longListBoxItem.UpdateLayout();

    var grid = VisualTreeHelper.GetChild(longListBoxItem, 0);
    var grid1 = VisualTreeHelper.GetChild(grid, 0);
    var viewportControl = VisualTreeHelper.GetChild(grid1, 0) as ViewportControl;
    var contentPresenter1 = VisualTreeHelper.GetChild(viewportControl, 0) as ContentPresenter;
    var canvas1 = VisualTreeHelper.GetChild(contentPresenter1, 0);
    var canvas2 = VisualTreeHelper.GetChild(canvas1, 0);
    var ContentPresenter2 = VisualTreeHelper.GetChild(canvas2, 0);
    var border = VisualTreeHelper.GetChild(ContentPresenter2, 0);
    var grid2 = VisualTreeHelper.GetChild(border, 0) as Grid;
    ImageSource imgSource = (grid2.Background as ImageBrush).ImageSource;

    // doing other stuffs here...
}

But here I am not getting all the imagebrushes. Let, I have ten imagebrushes. But I am getting only two(most of the time the first and the last) imagebrushes which have sources and rest others' sources are empty.

Is there any wrong in my selection. Need help...

0

There are 0 answers