2014-11-24 50 views
0

,所以我有同樣的問題,因爲這個人.. WPF: Bind Collection with Collection to a ListBox with groups屬性含量更比一次.. WPF

我試圖執行建議的回答我的問題,但發現錯誤「屬性‘內容’不止一次「。唯一的區別是ID喜歡的用戶控制像這樣實現的:

這裏是我的C#代碼:

public class Dog 
{ 
    public int dogID { get; set; } 
    public String Name { get; set; } 

    List<Puppy> puppies { get; set; } 
} 

public class Puppy 
{ 
    public String Name { get; set; } 
} 

,這是XAML:

<UserControl x:Class="PetStore.Menu" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 

    <CollectionViewSource x:Name="dogs" Source="{Binding}" > 
     <CollectionViewSource.GroupDescriptions> 
      <PropertyGroupDescription PropertyName="Name" /> 
     </CollectionViewSource.GroupDescriptions> 
    </CollectionViewSource> 

    <DataTemplate x:Key="dogTemplate" DataType="Project"> 
     <StackPanel Orientation="Horizontal"> 
      <TextBlock Text="{Binding Name}" /> 
     </StackPanel> 
    </DataTemplate> 

    <ListBox ItemsSource="{Binding Source={StaticResource dogs}}"> 
     <ListBox.GroupStyle> 
      <GroupStyle HeaderTemplate="{StaticResource dogTemplate}" /> 
     </ListBox.GroupStyle> 

     <ListBox.ItemTemplate> 
      <DataTemplate DataType="Puppy"> 
       <ListBox ItemsSource="{Binding puppies}"> 
        <ListBox.ItemTemplate> 
         <DataTemplate DataType="Puppy"> 
          <TextBlock Text="{Binding Name}" /> 
         </DataTemplate> 
        </ListBox.ItemTemplate> 
       </ListBox> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</UserControl> 

任何幫助是極大的讚賞!

回答

1

你錯過了UserControl.Resources標籤:

<UserControl x:Class="Tackle.View.Menu" 
      ...> 

    <UserControl.Resources> <!-- You're missing this --> 

     <CollectionViewSource x:Key="dogs" Source="{Binding}" > <!-- Change x:Name to x:Key here --> 
      <CollectionViewSource.GroupDescriptions> 
       <PropertyGroupDescription PropertyName="Name" /> 
      </CollectionViewSource.GroupDescriptions> 
     </CollectionViewSource> 

     <DataTemplate x:Key="dogTemplate" DataType="Project"> 
      <StackPanel Orientation="Horizontal"> 
       <TextBlock Text="{Binding Name}" /> 
      </StackPanel> 
     </DataTemplate> 
    </UserControl.Resources> 

    <!-- here goes your window content --> 

錯誤消息告訴你,你做了什麼錯:你試圖設置Content屬性不止一次。當您將元素聲明爲控件的直接子元素時,則隱式設置該控件類型的[ContentProperty("...")]屬性中指定的屬性。對於ContentControl(及其子類UserControl),該屬性爲Content。如果您想要設置不同的屬性,或者將某些內容添加到集合/字典屬性中,則必須指定屬性名稱。這意味着要麼使用Property="value"屬性語法,要麼使用<Owner.Property>元素語法。