【发布时间】:2009-04-22 11:32:31
【问题描述】:
任何人都可以从这段代码中想到为什么 ItemsSource 行会得到一个
Items 集合之前必须为空 使用 ItemsSource。
错误?我发现的大多数解决方案都指向不正确的 XAML,例如我似乎没有的额外元素等。当我拿出来时
ItemsSource="{绑定客户}"
它运行时没有错误(但当然不会显示我的客户列表)。
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,0,0,8"
/>
</ItemsControl>
</DockPanel>
</UserControl>
回答:
我确实有格式错误的 XAML,只是忽略了它,按钮应该在 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"
/>
【问题讨论】:
-
只是提到格式错误的 XAML 对我有帮助