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

Edw*_*uay 11 c# wpf mvvm

任何人都可以从这个代码中想出为什么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());
Run Code Online (Sandbox Code Playgroud)

有什么建议去哪儿看?

<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>
Run Code Online (Sandbox Code Playgroud)

回答:

我确实有错误的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"
    />
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 9

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

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