【问题标题】:VisualTreeHelper.GetChildrenCount returns wrong count Wp8VisualTreeHelper.GetChildrenCount 返回错误的计数 Wp8
【发布时间】:2015-02-25 10:58:20
【问题描述】:
  <ListBox x:Name="my_list" Grid.Row="0" Margin="0,34,0,10">
            <ItemsControl.ItemTemplate >
                <DataTemplate >
                    <StackPanel Orientation="Horizontal" >
                        <CheckBox x:Name="cbx_state"  Tag="{Binding}" Checked="cbx_state_Checked" Unchecked="cbx_state_Unchecked" />
                        <StackPanel Orientation="Vertical">
                            <TextBlock x:Name="txt_string" Text="{Binding}" VerticalAlignment="Center" FontSize="34" />
                            <TextBlock x:Name="txt_string1" Text=" Text " VerticalAlignment="Center" FontSize="20" />
                        </StackPanel>

                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ListBox>

我已经将列表框与包含超过 10 个项目的列表绑定在一起。我所做的是在应用程序栏菜单项上单击我想检查所有复选框。但是我实施的这种方法有不同的行为。有时孩子数是返回少于实际计数。方法是:

 private void GetItemsRecursive(DependencyObject lb)
    {
        var childrenCount = VisualTreeHelper.GetChildrenCount(lb);

        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(lb, i);

            if (child is CheckBox)
            {
                CheckBox targeted_element = (CheckBox)child;

                targeted_element.IsChecked = true;

                if (targeted_element.IsChecked == true)
                {

                    return;
                }
            }

            GetItemsRecursive(child);
        }
    }

我每次都将 childrenCount 设为不同的值,因此导致一些复选框未选中。

【问题讨论】:

  • 你认为这段代码会做什么?
  • 它检查列表框下的所有复选框
  • 您可能会让您的代码工作,但有更好的方法来实现您正在尝试做的事情。 (检查是否检查了列表中的任何项目?)。我建议阅读有关 MVVM 的内容。

标签: c# windows-phone-8


【解决方案1】:

ListBox 使用虚拟化容器。这意味着这些项目仅在需要时才加载(或多或少在屏幕上显示之前)。

您可以将默认的Listbox.ItemsPanel 更改为StackPanel

<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel/>
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>

但是,这可能会损害您应用的性能,尤其是在列表较长的情况下。您已经在为您的复选框使用绑定。最好的解决方案是依赖 MVVM - 添加一个 Checked 绑定,而不是调用 GetItemsRecursive,而是在 ViewModel 上执行一个设置 List-ViewModel 选中属性的命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 2019-08-25
    • 2017-03-19
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多