将ListBox数据绑定到包含Observable Collection的类的列表

时间:2012-05-23 21:45:59

标签: c# wpf silverlight

我有一个自定义类的项目列表。该类包含另一个类的可观察集合,该类具有两个字符串值。我希望数据绑定到其中一个字符串值,基于另一个。所以作为一个虚构的例子:

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; }
}

然后我将列表框绑定到Person列表:

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用于显示集合中的第一个项目,但是对于列表中的第二个项目,它是错误的,因为狗是colelction中的第二个项目:

        <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>

任何人都可以就如何实现这个目标提供一些指导吗?

1 个答案:

答案 0 :(得分:2)

使用值转换器仅显示狗。

XAML:

<TextBlock Text="{Binding Pets, Converter={StaticResource FindDogConverter}}" />

代码背后:

public class FindDogConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        IEnumerable<Pet> pets = value as IEnumerable<Pet>;
        return pets.Single(p => p.AnimalType == "Dog").Name;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}