小鱼塘

  • 小玩意
  • 小想法
记录自己技术和想法地方
  1. 首页
  2. Uncategorized
  3. 正文

wpf ItemsSource 正在使用时操作无效 异常

3月 25, 2020 144点热度 0人点赞 0条评论
内容纲要

背景:

自己在用listview添加数据的突然出现问题,直接蒙蔽了,因为自己用WPF不是很久。

找原因过程:

异常信息:

ItemsSource 正在使用时操作无效

说明是与ItemsSource有关。

我的代码:

void InitUI()
{
var AllRule = Service.GetAllRule();
if (AllRule != null && AllRule.Length > 0)
{
GroupRuleListView.ItemsSource = AllRule; //直接设置读取配置的数据源
}
}

添加数据的导致崩溃的地方:

if(RuleWindow.rule != null)
{
Service.AddRule(RuleWindow.rule);
GroupRuleListView.Items.Add(RuleWindow.rule);//添加就会崩溃
}

那么我直接不用数据源,我直接一个一个配置添加就可以解决问题。

void InitUI()
{
var AllRule = Service.GetAllRule();
if (AllRule != null && AllRule.Length > 0)
{
// GroupRuleListView.ItemsSource = AllRule; 不能这样子否者数据会有问题,用默认数据源
foreach(var item in AllRule)
{
GroupRuleListView.Items.Add(item);
}
}
}

本质问题:

我们通过F12查看代码(vs2019设置选项就可以查看源代码,见我以前的博客文章)。

对�0�2 GroupRuleListView.Items.Add(RuleWindow.rule);�0�2 add进行查看

看到代码:

//
// 摘要:
// Adds an item to the System.Windows.Controls.ItemCollection.
//
// 参数:
// newItem:
// The item to add to the collection.
//
// 返回结果:
// The zero-based index at which the object is added or -1 if the item cannot be
// added.
//
// 异常:
// T:System.InvalidOperationException:
// The item to add already has a different logical parent.
//
// T:System.InvalidOperationException:
// The collection is in ItemsSource mode.
public int Add(object newItem)
{
CheckIsUsingInnerView();
int result = _internalView.Add(newItem);
ModelParent.SetValue(ItemsControl.HasItemsPropertyKey, BooleanBoxes.TrueBox);
return result;
}

CheckIsUsingInnerView();�0�2关键代码

private void CheckIsUsingInnerView()
{
if (IsUsingItemsSource)
{
throw new InvalidOperationException(SR.Get(“ItemsSourceInUse”));
}
EnsureInternalView();
EnsureCollectionView();
VerifyRefreshNotDeferred();
}

这些代码来判断是否内部view,�0�2因为我们设置ItemSource ,那么就是用的外部,所以异常。

GroupRuleListView.Items.Add�0�2默认用的内部的,可以自己看代码分析。

标签: 暂无
最后更新:3月 25, 2020

小鱼儿

爱研究技术,爱玩LOL

点赞
< 上一篇
下一篇 >

COPYRIGHT © 2022 小鱼塘. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

湘ICP备18005349号