C#Windows Phone从代码中访问DataTemplate内部的图像控件

时间:2014-05-12 18:33:16

标签: c# image windows-phone-8 datatemplate longlistselector

我在LongListSelector DataTemplate中有一个名为“imgGameList”的图像控件,我想从代码中访问它,但是我无法从代码中找到控件。

我的LongListSelector和我的图像控件:

<phone:LongListSelector Name="llsGameList" ItemsSource="{Binding}" Tap="llsGameList_Tap" Margin="0,90,0,0">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Image Name="imgGameList" Margin="0,10,0,10" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Top" Height="200" Width="150">
                    <Image.Source>
                        <BitmapImage UriSource="{Binding BoxArtFrontThumb}"
                                 CreateOptions="BackgroundCreation" DecodePixelHeight="200" DecodePixelWidth="150" />
                    </Image.Source>
                </Image>
            </Grid>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

我尝试访问图像控件的原因是因为我遇到了内存问题,并希望对其应用gleb.kudr修复:Why do I get an OutOfMemoryException when I have images in my ListBox?

我希望有人可以帮助我。感谢。

1 个答案:

答案 0 :(得分:0)

    public FrameworkElement SearchVisualTree(DependencyObject targetElement, string elementName)
    {
        FrameworkElement res = null;
        var count = VisualTreeHelper.GetChildrenCount(targetElement);
        if (count == 0)
            return res;

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(targetElement, i);
            if ((child as FrameworkElement).Name == elementName)
            {
                res = child as FrameworkElement;
                return res;
            }
            else
            {
                res = SearchVisualTree(child, elementName);
                if (res != null)
                    return res;
            }
        }
        return res;
    }

用法:

Image image = SearchVisualTree(listItem, "imgGameList") as Image;