2011-04-15 35 views
3

我想做某事像这样的一个:结合收集减少其属性

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

当然RoomAccesses.Select(P => p.Room)给出的语法错误,但你得到这个想法。我想要在这里绑定roomaccesses-object中的所有房间。

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

Thx!

回答

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}"/> 
+0

我觉得这是非常超大,但在我的TreeView情况似乎没有更好的解决办法.. 。 非常感谢! :) – David 2011-04-16 18:01:08

1

你在这个例子中绑定了什么?

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

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

然后更新您的绑定路径只是RoomAccessed(或任何你想调用它)

1

在你的DataContext公开一个房间属性:

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

,并结合Rooms,而不是RoomAccesses

1

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