1

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

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;

如果动物类型是狗,我想绑定人名和宠物名。我知道我可以使用索引器进行绑定,但我特别需要狗条目,即使它是宠物集合中的第二个条目。下面的 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>

任何人都可以就我如何做到这一点提供一些指导吗?

4

1 回答 1

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();
    }
}
于 2012-05-23T22:06:29.850 回答