首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WP7 - VisualTreeHelper遍历所有ListBox项

WP7 - VisualTreeHelper遍历所有ListBox项
EN

Stack Overflow用户
提问于 2012-03-28 04:25:12
回答 1查看 1.7K关注 0票数 2

我需要基于选定(选中)的项创建新的ListBox。如果我在ListBox上只有20个项目,那么下面的代码实际上是有效的,但是添加更多的项目会使它崩溃。有没有人知道如何让它工作,或者有不同的方法?在listBox中循环有限制吗?

代码语言:javascript
复制
    // worked fine for 20 items,
    // but my actual list contems 95 items...
    private void btnCreateNewList_Click(object sender, RoutedEventArgs e)
    {

                int totalItemsCB = ListCheckBoxVocabulary.Items.Count;
                for (int ii = 0; ii < totalItemsCB-1; ii++)
                {
                    ListBoxItem item = this.ListCheckBoxVocabulary.ItemContainerGenerator.ContainerFromIndex(ii) as ListBoxItem;
                    CheckBox thisCheckBox = FindFirstElementInVisualTree<CheckBox>(item);
                    if (thisCheckBox.IsChecked == true) 
                    {

                        dataPlayListSource.Add(new SampleData() { Text = thisCheckBox.Content.ToString() + " | " + ii });
                        // this.PlayListCheckBoxVocabulary.UpdateLayout();
                        this.PlayListCheckBoxVocabulary.ItemsSource = dataPlayListSource;
                    }

                }
    }

    private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
    {
        var count = VisualTreeHelper.GetChildrenCount(parentElement);
        if (count == 0)
            return null;

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(parentElement, i);

            if (child != null && child is T)
            {
                return (T)child;
            }
            else
            {
                var result = FindFirstElementInVisualTree<T>(child);
                if (result != null)
                    return result;

            }
        }
        return null;
    }

和xaml:

代码语言:javascript
复制
        <controls:PivotItem Header="Vocabulary" >
            <ListBox x:Name="ListCheckBoxVocabulary" Margin="0,0,-12,0" ItemsSource="{Binding Items}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <!--<StackPanel Margin="0,0,0,17" Width="432">-->
                        <CheckBox x:Name="cbVocabulary" Content="{Binding Text}" Checked="CheckBox_Checked" Unchecked="UncheckBox" />
                        <!--</StackPanel>-->
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </controls:PivotItem>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-28 08:42:48

这个列表是虚拟的--控件是在需要的时候创建的,并且可能会被重用(我认为)。

您的选择是将ListBox设置为不虚拟化(覆盖模板,对于容器,而不是SerializedStackPanel,选择常规的StackPanel)。

您的另一个(也是更可取的)选择是通过数据绑定进行检查。在大多数情况下更容易和更快。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9897141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档