Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}">
    <TextBlock 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!

like image 338
David Avatar asked Jun 12 '26 10:06

David


2 Answers

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}"/>
like image 56
H.B. Avatar answered Jun 14 '26 00:06

H.B.


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

like image 39
Thomas Levesque Avatar answered Jun 14 '26 00:06

Thomas Levesque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!