[英]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.