【问题标题】:C# Windows Phone access image control inside DataTemplate from codeC# Windows Phone 从代码中访问 DataTemplate 中的图像控件
【发布时间】:2014-05-12 18:33:15
【问题描述】:

我在 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?

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

【问题讨论】:

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


    【解决方案1】:
        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;
    

    【讨论】:

    • 谢谢。你能告诉我这是否比用户 pm_2 在此发布的修复更有效:stackoverflow.com/questions/15189715/…
    • 我看到了同样的方法
    • 谢谢。它工作正常,我现在可以访问我的图像控件,但是当我将图像源设置为 null 时,它只是我的 LongListSelector 中被删除的第一个图像?你知道为什么吗?例如:我的 LongListSelector 中显示了 20 张图像,当我按下按钮时,我希望删除所有图像以释放内存,但是当我尝试这样做时,只有第一张图像被删除,而不是其他 19 张图像,我希望你明白我想做什么,最后我想在我不使用图像时从图像中释放内存。谢谢。
    • 您应该遍历列表中的所有项目并分别对每个项目调用SearchVisualTree
    • 如何在 selection_changed 事件中获取 listitem。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2013-06-19
    • 2016-03-16
    • 1970-01-01
    • 2012-04-10
    • 2016-01-19
    相关资源
    最近更新 更多