2009-04-22 22 views
11

任何人都可以從這段代碼變戲法之前Items集合必須是空的,爲什麼的ItemsSource線將得到一個這是爲什麼XAML得到的錯誤:使用的ItemsSource

Items collection must be empty before using ItemsSource.

錯誤?我發現的大多數解決方案都指向了錯誤組合的XAML,例如一個額外的元素等,我似乎沒有。當我拿出

ItemsSource="{Binding Customers}"

它運行時沒有錯誤(但當然不顯示我的客戶名單)。

客戶正是如此定義視圖模型,並在其3個CustomerViewModels:

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" 
    /> 
+0

剛剛提的格式不正確的XAML幫助,如果你忘記了你的控件的XML元素內的任何文字我 – stambikk 2017-10-06 00:19:35

回答

9

您正在嘗試設置的的ItemsSource ItemsControl但你已經有了孩子。哪兩個應該適用?你放在ItemsControl中的按鈕或者你將它作爲ItemsSource交給它的集合?錯誤消息是完全合理的。

您必須從ItemsControl中刪除按鈕或刪除ItemsSource屬性。您無法同時插入項目並設置ItemsSource。

+1

會出現同樣的錯誤:`<組合框的ItemsSource =「{結合客戶}」>這使得失敗`。 – 2011-01-14 16:12:37

2

Your ItemsControl中有一個Button。由於ItemsControl中已有一個項目,因此不會讓您設置其ItemsSource屬性。

將按鈕聲明向下移動到</ItemsControl>結束標記下。