Search code examples
windows-phone-8longlistselector

wp8 LongListSelector item add controls


I'm newbie on WP8, I need to add some random controls inside a ItemTemplate's StackPanel, but not work.

My code as:

<phone:LongListSelector
x:Name="TripResultsData"                    
SelectionChanged="TripResultsData_SelectionChanged"
ItemRealized="TripResultsData_ItemRealized"
IsGroupingEnabled="False"
Grid.Column="0"
Grid.Row="1">
<phone:LongListSelector.ItemTemplate>
    <DataTemplate>
        <StackPanel>

            <Image ... />
            <TextBlock ... />
                <TextBlock ... />
            <Image ... />

            <StackPanel x:Name="ImgContainer">

            <!-- Here I need to add n images -->

            </StackPanel>

        </StackPanel>
    </DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

I've tryed to inject the new components on event ItemRealized, but I've a error of NullExecption when i get the StackPanel on Item.

private void TripResultsData_ItemRealized(object sender, ItemRealizationEventArgs e)
{
    if (e.ItemKind == LongListSelectorItemKind.Item)
    {
        StackPanel imgBox = (StackPanel)e.Container.FindName("ImgContainer");

        Image img = new Image();
        img.Source = new BitmapImage(new Uri("/Assets/images/[email protected]", UriKind.RelativeOrAbsolute));

         imgBox.Children.Add(img);
    }
}

Thank you everyone for read me.


Solution

  • you can do that Providing ImageSource in its binding.

    XAML:

    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Image ... />
                <TextBlock ... />
                <TextBlock ... />
                <Image ... />
                <StackPanel x:Name="ImgContainer">
                <ListBox ItemsSource="{Binding ImgCollection}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Source="{Binding imgPath}"></Image>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
    

    CS:

    class ImgCollection
    {
        public string imgPath { get; set; }
        public ImgCollection() { }
    
        public ImgCollection(string imgPath) 
        {
            this.imgPath = imgPath;
        }
    }
    
     List<ImgCollection> obj = new List<ImgCollection>();
     obj.Add(new ImgCollection("img path 1"));
     obj.Add(new ImgCollection("img path 2"));
     obj.Add(new ImgCollection("img path 3"));
     obj.Add(new ImgCollection("img path 4"));
     TripResultsData.ItemSource = obj;