1
在下面的代碼中,在ColumnsListBox_Loaded
事件中,此方法對最後幾個ListBox項返回null。任何想法爲什麼會發生?我將數據綁定到ChildWindow類的OnOpned()事件中的列表框中,然後在ListBox類的Loaded()事件中檢索這些項目。ItemContainerGenerator.ContainerFromItem對最後幾項返回null
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;
}
}