我循环浏览列表视图中的每个项目,并格式化网格视图中的文本框。初始格式有效,但如果我上下滚动列表视图几次,格式就会消失。
这是处理我的项目的基本循环:
for (int i = 0; i < lvDocumentation.Items.Count; i++)
{
// Grabs the item
ListBoxItem selectedListBoxItem = lvDocumentation.ItemContainerGenerator.ContainerFromItem(lvDocumentation.Items[i]) as ListBoxItem;
PersonDTO thisPersonDTO = (PersonDTO)lvDocumentation.Items[i];
// I do some odds and ends here and call formatting routines for the buttons...
}
稍后,在我对此PersonDTO进行一些检查后,我根据人员状态格式化所选ListBoxItem
// Textblock
foreach (var item in UiCommon.FindVisualChildren<TextBlock>(selectedListBoxItem))
{
if (item.Name.ToLower() == textblockName.ToLower())
{
if (docPresent)
{
//item.Background = backgroundColor;
item.Foreground = Brushes.Green;
}
else
{
((TextBlock)item).Foreground = Brushes.Red;
}
}
}
// Button
foreach (var item in UiCommon.FindVisualChildren<Button>(selectedListBoxItem))
{
if (item.Name.ToLower() == buttonName.ToLower())
{
if (item.GetType().Name == "Button")
{
if (docPresent)
{
//item.Background = backgroundColor;
item.IsEnabled = true;
}
else
{
//item.Background = backgroundColor;
((Button)item).IsEnabled = false;
}
}
}
}
该代码有效并且格式正确(只要listBoxItem在显示中,但那是另一回事(
一旦过程完成,按钮的颜色就会被设置。
如果我上下滚动一点,颜色就会恢复到原来的格式,我不知道为什么。我到处都有断点,但没有看到任何代码在执行。
当我尝试格式化尚未显示的列表框项目时,我意识到存在格式化问题。我使用这段代码:
lvDocumentation.UpdateLayout();
lvDocumentation.ScrollIntoView(lvDocumentation.Items[index]);
selectedListBoxItem = lvDocumentation.ItemContainerGenerator.ContainerFromItem(lvDocumentation.Items[index]) as ListBoxItem;
如果该项目最初返回null,因为它不在显示区域中,那么它将获得列表框项目,而不是null。
似乎有什么东西在刷新格式,但不知道为什么/在哪里?
如果我上下滚动一点,颜色会恢复到原来的格式,我不知道为什么。
这是因为文档中描述了默认的UI虚拟化和容器回收。
您可以通过将附加的IsVirtualizing
属性设置为false
:来禁用虚拟化
VirtualizingPanel.SetIsVirtualizing(lvDocumentation, false);
这是以牺牲滚动性能为代价的,但考虑到您当前直接操作UI容器的方法,这是您唯一的选择。
您应该研究MVVM。这是在开发基于XAML的UI应用程序时推荐使用的设计模式。