所以我和这个人有同样的问题.. WPF: Bind Collection with Collection to a ListBox with groups
我尝试对我的问题实施建议的答案,但发现错误“属性'内容'设置了多次”。唯一的区别是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>
非常感谢任何帮助!!
答案 0 :(得分:2)
您错过了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>
元素语法。