[英]WPF Unable to get ListBoxItem by item or by index after 7th item
我有一個奇怪的問題,我嘗試更新ListBoxItem中包含的復選框的檢查狀態,在嘗試了幾種方法使第7個項目工作后,我無法獲得ListBoxItem,如以下方法所示。 itemIndex每次確實有一個正值(所以我知道正在找到該項目),但是為什么它不能獲取listboxitem我不知道
private IEnumerable<CheckBox> GetListBoxItemCheckBoxes(object item)
{
var itemIndex = LstItems.Items.IndexOf(item);
var selectedListBoxItem = LstItems.ItemContainerGenerator.ContainerFromIndex(itemIndex) as ListBoxItem;
var selectedListBoxItemCheckBoxes = selectedListBoxItem?.FindVisualChildrenOfType<CheckBox>();
if (selectedListBoxItemCheckBoxes == null)
{
selectedListBoxItem = LstItems.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
selectedListBoxItemCheckBoxes = selectedListBoxItem?.FindVisualChildrenOfType<CheckBox>();
if (selectedListBoxItemCheckBoxes == null)
{
itemIndex = LstItems.ItemContainerGenerator.Items.IndexOf(item);
selectedListBoxItem = LstItems.ItemContainerGenerator.ContainerFromIndex(itemIndex) as ListBoxItem;
selectedListBoxItemCheckBoxes = selectedListBoxItem?.FindVisualChildrenOfType<CheckBox>();
}
}
return selectedListBoxItemCheckBoxes;
}
我認為這可能與我添加該項目后嘗試設置復選框狀態的時間有關? 我讀過有關這方面的SO,但至今都未已經能夠幫助我與我的問題了幾個問題,我想這個答案可能是接近..但它給了我同樣的結果: https://開頭計算器的.com /一個/一百八十零萬零一百四十分之二千三百五十零萬一千三百七十八
這些項目未綁定,而是使用ListBox.Items.Add(對綁定不太熟悉)添加的。
我也在后台線程中執行此操作,因為我需要定期刷新列表框的內容,並且需要進行api調用。
用於更新列表框內容的方法如下。 SetItemChecked
調用第一個方法來獲取復選框,但是在第7個項目之后SetItemChecked
開始返回null
public void ResetAndAddItems<T>(IEnumerable<T> items, string displayByProperty = "",
Func<T, string> displayByFunc = null,
Dictionary<string, bool> checkedStates = null,
Func<ListItem<T>, Dictionary<string, bool>, bool> checkedStatesKeyFunc = null)
{
Dispatcher.Invoke(() =>
{
LstItems.Items.Clear();
});
var listedItems = items?.ToList();
if (listedItems == null || !listedItems.Any())
{
return;
}
foreach (var item in listedItems)
{
var listItem = new ListItem<T>
{
DisplayByProperty = displayByProperty,
DisplayByFunc = displayByFunc,
Item = item
};
Dispatcher.Invoke(() =>
{
LstItems.Items.Add(listItem);
if (checkedStates != null && checkedStatesKeyFunc != null)
{
SetItemChecked(item, checkedStatesKeyFunc(item as ListItem<T>, checkedStates));
}
});
}
}
默認情況下,ListBoxes上的UI虛擬化設置為True。 而且,如果啟用了UI虛擬化,則只會為可見項創建容器。 嘗試設置此附加屬性:
VirtualizingStackPanel.IsVirtualizing="False"
為了解決這個問題,我不得不進行綁定。
問題是,因為一次只有7個項目顯示在列表視圖上,所以僅繪制了7個項目,要解決這個問題,我可以滾動到第7個項目之后的下一個項目,依此類推,但是速度明顯慢一些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.