我有一个自定义类的项目列表。 该类包含一个可观测到的另一类的收藏, 包含两个字符串值。 我要根据另一个字符串的某个值将数据绑绑到一个字符串值中。 因此, 一个虚构的例子 :
public class Person
{
public string Name { get; set; }
public ObservableCollection<Pet> Pets { get; set; }
}
public class Pet
{
public string AnimalType { get; set; }
public string Name { get; set; }
}
然后把列表框绑在个人名单上:
List<Person> people = new List<Person>();
Person p = new Person() { Name = "Joe", Pets = new ObservableCollection<Pet>() { new Pet() { Name = "Spot", AnimalType = "Dog" }, new Pet() { Name = "Whiskers", AnimalType = "Cat" } } };
people.Add(p);
p = new Person() { Name = "Jim", Pets = new ObservableCollection<Pet>() { new Pet() { Name = "Juniper", AnimalType = "Cat" }, new Pet() { Name = "Butch", AnimalType = "Dog" } } };
people.Add(p);
p = new Person() { Name = "Jane", Pets = new ObservableCollection<Pet>() { new Pet() { Name = "Tiny", AnimalType = "Dog" }, new Pet() { Name = "Tulip", AnimalType = "Cat" } } };
people.Add(p);
MyListBox.ItemsSource = people;
如果动物类型是 Dog, 我想绑定一个人的名字和宠物的名字。 我知道可以使用索引器绑定它, 但我特别需要狗的条目, 即使它是宠物收藏中的第二个条目。 下面的 XAML 用于显示收藏中的第一个条目, 但对于列表中的第二个条目, 它是错误的, 因为狗是折叠中的第二个条目 :
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Height="55.015" Width="302.996">
<TextBlock TextWrapping="Wrap" Text="{Binding Name}" Height="25.015" VerticalAlignment="Top" Margin="0,0,8,0"/>
<TextBlock Text="{Binding Pets[0].Name}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
谁能为我如何完成这个任务指点点什么?