wp8 LongListSelector项添加控件

时间:2014-06-16 12:34:52

标签: windows-phone-8 longlistselector

我是WP8的新手,我需要在ItemTemplate的StackPanel中添加一些随机控件,但不能正常工作。

我的代码为:

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

我尝试在事件ItemRealized上注入新组件,但是当我在Item上获得StackPanel时,我的NullExecption错误。

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/ico_eurocity_obbdb@2x.png", UriKind.RelativeOrAbsolute));

         imgBox.Children.Add(img);
    }
}

谢谢大家的阅读。

1 个答案:

答案 0 :(得分:1)

您可以在其ImageSource中提供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;