我有一个具有这种结构的对象
public class Parent
{
public string Name {get; set;}
public int ID {get; set;}
public List<Child> Children{set; get;}
public Address HomeAddress {get; set;}
}
我使用ObjectToObservableListConverter为地址、父级、子级创建了一个分层模板
public class ObjectToObservableListConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
return new ObservableCollection<Graphic> { (value as Graphic) };
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
和PropertyToListConverter
public class PropertyToListConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Type type = value.GetType();
PropertyInfo[] propertyList = value.GetType().GetProperties();
List<object> values =
(from property in propertyList
//where property.GetCustomAttributes(typeof(NotForTreeViewAttribute), false).Count() == 0
select property.GetValue(value, BindingFlags.Default, null, null, CultureInfo.InvariantCulture)).ToList();
return values;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我创建的模板是:
<TreeView ItemsSource="{Binding Path=Parent,
Converter={StaticResource ResourceKey=objectToListConverter},
UpdateSourceTrigger=PropertyChanged}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type en:Parent}"
ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,4,0,0"
VerticalAlignment="Center"
FontWeight="Bold"
Text="Children" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type en:Child}"
ItemsSource="{Binding Converter={StaticResource ResourceKey=propertyToListConvertor}}">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,4,0,0"
VerticalAlignment="Center"
FontWeight="Bold"
Text="{Binding Path=ChildName}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type en:Address}"
ItemsSource="{Binding Converter={StaticResource ResourceKey=propertyToListConvertor}}">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0,4,0,0"
VerticalAlignment="Center"
FontWeight="Bold"
Text="AddressType" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
如果我在 Parent 上创建模板并设置 Children 属性的 ItemsSource 路径,我不会获取 Parent 的剩余属性。或者,如果我将 ItemsSource 设置为 Parent 类型的属性和 user 属性以列出转换器,我不会得到子级的层次结构。
我错过了什么?
请帮忙。提前致谢