为什么此XAML会收到错误:在使用ItemsSource之前,Items集合必须为空
任何人都可以从这个代码中想出为什么ItemsSource行会得到一个
在 使用ItemsSource 之前,项集合必须为空 。
错误? 我发现的大多数解决方案都指向不合理的XAML,例如我似乎没有的额外元素等。 当我拿出来
ItemsSource =“{绑定客户}”
它运行没有错误(但当然不显示我的客户列表)。
客户因此在ViewModel中定义并且其中包含3个CustomerViewModel:
Customer[] customers = Customer.GetCustomers(); IEnumerable customersViewModels = customers.Select(c => new CustomerViewModel(c)); this.Customers = new ReadOnlyCollection(customersViewModels.ToArray());
有什么建议吗?
回答:
我确实有错误的XAML,只是忽略了它, Button应该在ItemsControl之外 :
您正在尝试设置ItemsControl的ItemsSource,但您已经有了子项。 哪两个应该适用? 您放在ItemsControl中的Button或您将其作为ItemsSource处理的集合? 错误消息非常合理。
您必须从ItemsControl中删除该按钮或删除ItemsSource属性。 您不能同时插入项目和设置ItemsSource。
您的ItemsControl中有一个Button。 由于ItemsControl中已有一个项目,因此不允许您设置其ItemsSource属性。
将Button声明向下移动到结束标记下。
你看过这个问题吗? 这似乎是你的问题的答案。
“在使用ItemsSource之前,项目集合必须为空。”