0

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...

raisul
  • 640
  • 1
  • 5
  • 26
  • To get an element inside a data template, use Template.FindName. – aybe Nov 11 '14 at 09:22
  • @raisul Why not just uses your binding? it would be `((model_collection)AllPhotosListBox.ItemsSource))[i].ImageUrlLow` or you can just use your PhotoItems[i].ImageUrlLow, you shouldn't need to browse the VisualTree unless you something very distinct. – Chubosaurus Software Nov 11 '14 at 21:52
  • Actually I am using VisualTreeHelper to nullify the specific ImageSource so that it no longer holds or caches the content of image. – raisul Nov 12 '14 at 07:15

0 Answers0