![](/img/trans.png)
[英]Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead
[英]Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead when execution twice
我有一段代码无法正常工作。 如果我执行btnNew一旦没有问题。 如果我执行两次,我会收到错误...
使用ItemsSource时,操作无效。 使用ItemsControl.ItemsSource访问和修改元素。
主要课程
ClassA obj = new ClassA();
private void btnNew_Click(object sender, RoutedEventArgs e)
{
//List strings for clearing and then creating new strings for Title combobox
ObservableCollection<string> calledList = obj.GetList();
cbTitle.Items.Clear();
cbTitle.ItemsSource = calledList;
}
ClassA.cs
private ObservableCollection<string> data = new ObservableCollection<string>();
public ObservableCollection<string> GetList()
{
return data;
}
public void SimpleNew()
{
data.Add("A");
data.Add("B");
}
如果我在主类中使用if语句它将消除问题然后它将在组合框中创建重复的字符串。 然后我问自己我是否需要创建一个处理不同的方法? 我不确定。
这是我在主类中的if语句
if (cbTitle.Items.Count == 0)
{
ObservableCollection<string> calledList = obj.GetList();
cbTitle.Items.Clear();
cbTitle.ItemsSource = calledList;
}
当我使用try / catch时,它会捕获错误并显示消息。 所以这也不好。
所以我的问题是谁能告诉我如何解决这个问题?
您不能同时设置ItemsSource
属性和 Items
属性。 尝试简单地删除对cbTitle.Items.Clear()
调用,如果你在下一行设置ItemsSource
属性,这是不必要的。
更新>>>
您只需要设置一次ItemsSource
属性,最好是在XAML中:
<ComboBox ItemsSource="{Binding Items}" ... />
完成后,您不应再次设置它。 要更改ComboBox
的项目,只需更改集合中的项目......它们现在是数据绑定的...这是WPF,而不是WinForms:
private void btnNew_Click(object sender, RoutedEventArgs e)
{
//List strings for clearing and then creating new strings for Title combobox
ObservableCollection<string> calledList = obj.GetList();
Items = calledList;
}
谢谢Sheridan。 我也发现如果我这样做......
ObservableCollection<string> calledList = obj.GetList();
calledList.Clear(); // I have to use this line of code
calledList.ItemsSource = calledList;
这解决了我的问题。 我没有使用xaml因为它给了我问题。 您可能还记得我在浏览记录时打开了关于组合框的线程。 我设法通过使用for循环解决了这个问题。 看看我的其他线程,如果你愿意的话, 在这里
然而,这不是最终的解决方案。 我正在学习wpf和它的反刍操作,所以我会发现它会很有趣
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.