在下面的代码中,在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;
}
}