绑定到收集减少到其属性之一

时间:2011-04-15 15:06:37

标签: c# wpf xaml data-binding

我想这样做:

<HierarchicalDataTemplate 
                          x:Key="BuildingTemplate"
                          ItemsSource="{Binding Path=RoomAccesses.Select(p => p.Room)}"
                          ItemTemplate="{StaticResource ZoneTemplate}">
    <TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>

当然 RoomAccesses.Select(p =&gt; p.Room)会出现语法错误,但你明白了。我希望roomaccesses-object中的所有房间都被绑定在这里。

你有任何想法如何正确地做到这一点吗?

THX!

4 个答案:

答案 0 :(得分:1)

在这个例子中你有什么约束力?

如果您可以编辑要绑定的类,可以像这样向类添加属性:

public IEnumberable<string> RoomsAccessed // replace string with the type of Room
{
    get { return RoomAccesses.Select(p => p.Room); }
}

然后将您的绑定路径更新为RoomAccessed(或任何您想要的名称)

答案 1 :(得分:1)

在DataContext中公开Rooms属性:

public IEnumerable<Room> Rooms
{
    get { return RoomAccesses.Select(p => p.Room); }
}

并绑定到Rooms而不是RoomAccesses

答案 2 :(得分:1)

为什么不按原样保留绑定,比如ItemsSource =“{Binding Path = RoomAccesses}”,然后处理datatemplate中的.Room属性?我的意思是使用PropertyPath很容易做到。

答案 3 :(得分:1)

您可以做的其他事情是使用ValueConverter,例如这是一个简单的属性选择转换器:

public class SelectConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!(value is IEnumerable)) throw new Exception("Input is not enumerable");
        IEnumerable input = ((IEnumerable)value);
        var propertyName = parameter as string;
        PropertyInfo propInfo = null;
        List<object> list = new List<object>();
        foreach (var item in input)
        {
            if (propInfo == null)
            {
                propInfo = item.GetType().GetProperty(propertyName);
                if (propInfo == null) throw new Exception(String.Format("Property \"{0}\" not found on enumerable element type", propertyName));
            }
            list.Add(propInfo.GetValue(item, null));
        }
        return list;
    }

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

XAML使用示例:

<ListBox ItemsSource="{Binding Data,
                               Converter={StaticResource SelectConverter},
                               ConverterParameter=Occupation}"/>
相关问题