【问题标题】:Databinding ListBox to a List of a Class that Contains an Observable Collection将 ListBox 数据绑定到包含可观察集合的类的列表
【发布时间】:2012-05-23 21:45:59
【问题描述】:

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

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;

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

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

【问题讨论】:

    标签: c# wpf silverlight


    【解决方案1】:

    使用值转换器仅显示狗。

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

    【讨论】:

    • 谢谢。看起来我可以使用转换器参数来保持它的通用性,所以这正是我所需要的。
    猜你喜欢
    • 2011-12-03
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多