Reputation: 1687
I want to have a two level TreeView
in WPF
, but it doesn't show the second level.
My first class
ist
public class MyClass : BaseViewModel
{
#region Fields
public ObservableCollection<MySubClass> SubClassCollection
{
get;
private set;
}
#endregion Fields
#region Propertys
public string Name
{
get
{
return Model.Name;
}
}
#endregion Propertys
}
And then i got my MySubClass
public class MySubClass : BaseViewModel
{
#region Propertys
public string Name
{
get
{
return Model.Name;
}
}
public int Number
{
get
{
return Model.Number;
}
}
#endregion Propertys
}
And my XAML
looks like this:
<TreeView ItemsSource="{Binding Path=MyClassCollection, Mode=OneWay}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type vm:MyClass}">
<Grid>
<TextBlock Text="{Binding Name}" Foreground="{DynamicResource AccentColorBrush}" />
</Grid>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type vm:MySubClass}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="19"></ColumnDefinition>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Number}"
HorizontalAlignment="Left"
/>
<StackPanel Orientation="Horizontal"
Grid.Column="1"
HorizontalAlignment="Left"
>
<TextBlock Text=" ("
Foreground="{DynamicResource AccentColorBrush}"
/>
<TextBlock Text="{Binding Name}"
Foreground="{DynamicResource AccentColorBrush}"
/>
<TextBlock Text=")"
Foreground="{DynamicResource AccentColorBrush}"
/>
</StackPanel>
</Grid>
</DataTemplate>
</TreeView.Resources>
</TreeView>
But it shows me only a List of MyClass
without the relative MySubClass
.
What am I doing wrong?
Upvotes: 0
Views: 94
Reputation: 35733
HierarchicalDataTemplate for MyClass is missing ItemsSource binding which provide data for nested levels
<HierarchicalDataTemplate DataType="{x:Type vm:MyClass}"
ItemsSource="{Binding Path=SubClassCollection}">
<TextBlock Text=" ("
Foreground="{DynamicResource AccentColorBrush}"/>
<TextBlock Text="{Binding Name}"
Foreground="{DynamicResource AccentColorBrush}"/>
<TextBlock Text=")"
Foreground="{DynamicResource AccentColorBrush}"/>
1 TextBlock with a StringFormat
parameter will do
<TextBlock Text="{Binding Name, StringFormat=' (\{0\})'}"
Foreground="{DynamicResource AccentColorBrush}" />
that probably makes StackPanel
redundant as well
Upvotes: 1