【发布时间】:2013-08-19 23:04:53
【问题描述】:
我的 XAML 中有列表框,几个复选框和过滤器按钮。我的应用程序会生成大量日志,这些日志会显示在列表框中。 当我在列表框中有数据时,此 XAML 将执行的操作是用户将选中\取消选中复选框。基于此,单击按钮时将过滤列表框中的数据。根据数据,我想在每个项目上显示不同的前景色和背景色。
private void FilterButton_Click ( object sender , RoutedEventArgs e )
{
//Whenever filter button is clicked, i will check for checkbox status. whichever //checkbox is ON I will add checkbox name into Dictionary. Then I will read string from Listbox and extract particular keyword from that and match with Dictionary key. If it //matches then I will modify the background and foreground color for that particualr //listbox items. My problem here is only certain Listbox items get updated rest of them are //unchaged. When debugged i found that itemcontainergenerator returns null for all other //items.
for ( int i = 0 ; i < ListBox1.Items.Count ; i++ )
{
ListBoxItem item1 = ( ListBoxItem )ListBox1.ItemContainerGenerator.ContainerFromIndex(i);
string recordType;
string [] contentArray;
if ( item1 == null )
continue;
if ( item1.Content == "" )
continue;
contentArray = item1.Content.ToString().Split( new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries );
recordType = contentArray [ 1 ];
if ( checkBoxType.ContainsKey ( recordType ))
{
//int code = RecordTypeToColorCode [ recordType ];
//item1.Foreground = ColorCodeToForeColor [ code ];
item1.Foreground = Brushes.DarkCyan;
item1.FontSize = 13;
item1.Background = Brushes.LightGoldenrodYellow;
}
else
{
item1.Foreground = Brushes.LightGray;
}
}
}
我看到的问题是,如果假设我的列表框有 1000 个项目,那么只有 35-40 个项目被更新。其余所有项目都相同。我对代码进行了更多调试,发现在某个数字 35-40 之后,所有项目都为空,这就是为什么我无法更新列表框中的所有项目。 我没有在我的代码中打开虚拟化。有什么办法可以更新所有项目。任何帮助表示赞赏。我在想 ItemCONtainerGenerator 是否有任何问题,因为它只显示某些项目,而且虚拟化也已关闭。
【问题讨论】:
-
@HighCore 每当单击过滤器按钮时,我都会检查复选框状态。无论哪个复选框打开,我都会将复选框名称添加到字典中。然后我将从 Listbox 中读取字符串并从中提取特定关键字并与 Dictionary 键匹配。如果它//匹配,那么我将修改该特定//列表框项目的背景和前景色。我的问题是只有某些列表框项目得到更新,其余的没有更新。调试时我发现 itemcontainergenerator 为所有其他项目返回 null。
-
我的观点仍然成立。您需要在 ViewModel 级别处理所有数据并单独保留 UI。发布您需要的屏幕截图,我可以告诉您在 WPF 中执行此操作的正确方法。
-
@HighCore 请看下面我附上截图的帖子。我已经有了该集合的 MVVM 模型。但我想根据内容过滤和修改模板