我想这样做:
<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 中的所有房间都绑定(bind)在这里。
您知道如何正确执行此操作吗?
谢谢!
最佳答案
您还可以使用 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}"/>
关于c# - 绑定(bind)到集合减少到它的属性之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5678717/