开发者

Binding to collection reduced to one of its properties

i want to do sth like this:

<HierarchicalDataTemplate 
                          x:Key="BuildingTemplate"
                          ItemsSource="{Binding Path=RoomAccesses.Select(p => p.Room)}"
                          ItemTemplate="{StaticResource ZoneTemplate}">
    <TextBl开发者_如何学JAVAock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>

Of course the RoomAccesses.Select(p => p.Room) gives syntax errors, but u get the idea. I want all the rooms in the roomaccesses-object to be bound here.

Do u have any ideas how to do this correctly?

Thx!


Something else you can do is use a ValueConverter, e.g. this is a simple property selection converter:

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 use example:

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


Expose a Rooms property in your DataContext:

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

and bind to Rooms instead of RoomAccesses


Why not leaving the binding as is, like ItemsSource="{Binding Path=RoomAccesses}", and then dealing with the .Room property in the datatemplate? I mean with a PropertyPath that's easy to do.


What are you binding to in this example?

If you can edit the class that you're binding to, you can add a property to the class like this:

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

Then update your Binding Path to just RoomAccessed (or whatever you want to call it)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜