zoukankan      html  css  js  c++  java
  • 【WPF】当 ItemsSource 正在使用时操作无效。改用 ItemsControl.ItemsSource 访问和修改元素

    问题:

    • 中文版报错:Additional information: 当 ItemsSource 正在使用时操作无效。改用 ItemsControl.ItemsSource 访问和修改元素。
    • 英文版报错:Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

    原因:前台XAML中ListBox之类的含多个条目的控件,它的ItemsSource绑定了ViewModel中的某个ObservableCollection< T >集合,但在Model中调用时尝试访问这个控件,并修改它的ItemsSource。如下面的写法会报错:

    <ListBox x:Name="designViewLB" ItemsSource="{Binding DesignViewList}">
    shellWindow.designViewLB.Items.Add(new DesignViewItem() {
        // ... 设置属性
    });

    解决:因为前台控件的ItemsSource已被绑定到某个集合中,所以不能再直接操作这个控件的ItemsSource,而应转为操作这个控件ItemsSource所绑定的集合。改为如下写法即可:

    shellViewModel.DesignViewList.Add(new DesignViewItem()
    {
        // ... 设置属性
    });
  • 相关阅读:
    ORACLE DROP TABLE和truncate table的区别
    C#版链表加强版
    C#版栈
    再谈为什么要使用MONO
    流浪猫伏击大白鹅
    编写ASP.NET复合控件实例
    C# 大文件拷贝
    关于团队项目构架设计的疑问
    在Windows平台下使用MONO
    C#版链表
  • 原文地址:https://www.cnblogs.com/guxin/p/wpf-operation-is-not-valid-while-itemssource-is-in-use.html
Copyright © 2011-2022 走看看