问题 为什么此XAML会收到错误:在使用ItemsSource之前,Items集合必须为空


任何人都可以从这个代码中想出为什么ItemsSource行会得到一个

之前项目集合必须为空 使用ItemsSource。

错误?我发现的大多数解决方案都指向不合理的XAML,例如:一个我似乎没有的额外元素等。当我拿出来

ItemsSource =“{绑定客户}”

它运行没有错误(但当然不显示我的客户列表)。

客户因此在ViewModel中定义并且其中包含3个CustomerViewModel:

Customer[] customers = Customer.GetCustomers();
IEnumerable<CustomerViewModel> customersViewModels = customers.Select(c => new CustomerViewModel(c));
this.Customers = new ReadOnlyCollection<CustomerViewModel>(customersViewModels.ToArray());

有什么建议吗?

<UserControl x:Class="TestCommandSink123.View.CustomersView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestCommandSink123"
    xmlns:view="clr-namespace:TestCommandSink123.View"
    xmlns:vm="clr-namespace:TestCommandSink123.ViewModel"
    xmlns:sink="clr-namespace:TestCommandSink123.CommandSinkClasses"
    sink:CommandSinkBinding.CommandSink="{Binding}"
    >

    <UserControl.CommandBindings>
        <sink:CommandSinkBinding Command="vm:CustomersViewModel.CloseAllCustomersCommand"/>
    </UserControl.CommandBindings>

    <DockPanel>
        <ItemsControl
            DockPanel.Dock="Bottom" ItemsSource="{Binding Customers}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <view:CustomerView/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <Button
                Command="vm:CustomersViewModel.CloseAllCustomersCommand"
                Content="Close All"
                Margin="0,0,0,8"
                />
        </ItemsControl>

    </DockPanel>
</UserControl>

回答:

我确实有错误的XAML,只是忽略了它, Button应位于ItemsControl之外

<ItemsControl
    DockPanel.Dock="Bottom" ItemsSource="{Binding Customers}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <view:CustomerView/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
<Button
    Command="vm:CustomersViewModel.CloseAllCustomersCommand"
    Content="Close All"
    Margin="0,0,0,8"
    />

11295
2018-04-22 11:32


起源

只是提到格式错误的XAML帮助了我 - stambikk


答案:


您正在尝试设置ItemsControl的ItemsSource,但您已经有了子项。哪两个应该适用?您放在ItemsControl中的Button或您将其作为ItemsSource处理的集合?错误消息非常合理。

您必须从ItemsControl中删除该按钮或删除ItemsSource属性。您不能同时插入项目和设置ItemsSource。


9
2018-04-22 11:36



如果您忘记了控件的XML元素中的任何文本,则会发生同样的错误: <ComboBox ItemsSource="{Binding Customers}">This makes it fail</ComboBox>。 - Marcel Gosselin


您的ItemsControl中有一个Button。由于ItemsControl中已有一个项目,因此不允许您设置其ItemsSource属性。

将Button声明向下移动到 </ItemsControl> 结束标签。


2
2018-04-22 11:36





你看过这个问题吗?这似乎是你的问题的答案。

“在使用ItemsSource之前,项目集合必须为空。”


1
2018-04-22 11:37