c# - 绑定(bind)到集合减少到它的属性之一

标签 c# wpf xaml data-binding

我想这样做:

<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/

相关文章:

c# - 使用正则表达式处理异常的问题

wpf - 数据绑定(bind)值未从其他线程更新

c# - MVVM 界面框架

c# - 调试/断点为什么 WPF BindingExpression 为空

c# - JetBrains Rider XAML 预览不可用

c# - 在不关闭或处理流的情况下通过 TCP 发送多个对象

c# - Linq 到实体 : using ToLower() on NText fields

c# - XML 解析 : Reading CDATA

wpf - MVVM/命令和控制模板

c# - 如何在 Windows Phone 的应用程序磁贴中伪造自己的应用程序磁贴