ItemContainerGenerator.ContainerFromItem为最后几个项返回null

时间:2012-01-04 04:45:41

标签: silverlight silverlight-4.0

在下面的代码中,在ColumnsListBox_Loaded事件中,此方法为最后几个ListBox项返回null。知道为什么会这样吗?我是ChildWindow类的OnOpned()事件中的列表框数据绑定,然后在ListBox类的Loaded()事件中检索这些项。

  public partial class SPListColumns : ChildWindow
    {
        Web site;
        List spList;
        ListItemCollection listItems;
        string listName;
        public DataGrid MainGrid;

        public SPListColumns(string listName, DataGrid MainGrid)
        {

            InitializeComponent();
            if (!string.IsNullOrEmpty(listName))
            {
                this.listName = listName;

            }

            this.MainGrid = MainGrid;
        }

        void ColumnsListBox_Loaded(object sender, RoutedEventArgs e)
        {

            foreach (DataGridTextColumn columnValue in ColumnsListBox.Items)
            {

                ListBoxItem li = ColumnsListBox.ItemContainerGenerator.ContainerFromItem(columnValue) as ListBoxItem;
                if (li != null)
                {

                    if (MainGrid.Columns.First(s => s.Header == columnValue.Header).Visibility == System.Windows.Visibility.Collapsed)
                    {
                        li.IsSelected = false;
                    }
                    else
                    {
                        li.IsSelected = true;
                    }

                }

            }
        }

        protected override void OnOpened()
        {
            base.OnOpened();
            ColumnsListBox.Loaded += new RoutedEventHandler(ColumnsListBox_Loaded);
            BindColumns(listName);
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;



            foreach (DataGridTextColumn columnValue in ColumnsListBox.Items)
            {

                ListBoxItem li = ColumnsListBox.ItemContainerGenerator.ContainerFromItem(columnValue) as ListBoxItem;
                if (li != null)
                {
                    if (!li.IsSelected)
                    {
                        MainGrid.Columns.First(s => s.Header == columnValue.Header).Visibility = System.Windows.Visibility.Collapsed;
                    }
                }

            }

        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void BindColumns(string listName)
        {

               ColumnsListBox.Items.Clear();
               ColumnsListBox.ItemsSource = MainGrid.Columns;
        }
    }

1 个答案:

答案 0 :(得分:1)

ListBox可能正在使用虚拟化来避免为未显示的项目生成容器(这就是为什么第一项可以正常工作的原因)。

请参阅these answers

您可能只想查看可见项目的容器;或继承ListBox以覆盖PrepareContainerForItemOverride以访问容器(如果您想要动态执行某些操作)或关闭虚拟化(将ItemsPanel更改为StackPanel而非VirtualizingStackPanel。)