加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么这个XAML得到错误:Items集合在使用ItemsSource之前

发布时间:2020-12-15 06:32:21 所属栏目:百科 来源:网络整理
导读:任何人都可以从这个代码中引发为什么ItemsSource行会得到一个 Items collection must be empty before using ItemsSource. 错误?我发现的大多数解决方案都指向不合格的XAML,例如一个额外的元素等,我似乎没有.当我拿出来 ItemsSource=”{Binding Customers}
任何人都可以从这个代码中引发为什么ItemsSource行会得到一个

Items collection must be empty before
using ItemsSource.

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

ItemsSource=”{Binding Customers}”

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

客户在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,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,8"
    />

解决方法

您正在尝试设置ItemsControl的ItemsSource,但您已经拥有子项.这两个应该适用哪一个?你放在ItemsControl中的Button或者您正在将其作为ItemsSource处理的集合?错误信息是完全合理的.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读