任何人都可以从这个代码中引发为什么ItemsSource行会得到一个
@H_502_34@解决方法
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" />