2011-04-15 36 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很容易做到。