i'm actually developping my first WPF application which must display all components of my computer in a treeview with hierarchical data.
Since yesterday i'm facing a little problem, i read tons of examples of treeview binding but I did not succeed with multiples types binding...
It must look like this :
My machine (level 0)
-----Keyboards⬇️(level 1)
--------Keyboard1⬇️(level 2)
--------Keyboard2⬇️(level 2)
-----OS⬇️(level 1)
-----CPU⬇️(level 1)
--------CPU1⬇️(level 2)
--------CPU2⬇️(level 2)
-----VideoCard⬇️(level 1)
---------VideoCard1⬇️(level 2)
---------VideoCard2⬇️(level 2)
I have a viewmodel with all my components device :
DeviceInfo.cs :
public class DeviceInfo
{
public string ComputerName { get; set; }
public Bios Bios { get; set; }
public ComputerSystem ComputerSystem { get; set; }
public List<Keyboard> Keyboards { get; set; }
public OperatingSystem OperatingSystem { get; set; }
public List<Processor> Processors { get; set; }
public List<VideoCard> VideoCards { get; set; }
}
Each component contain specific attribute, for example Keyboard.cs:
public class Keyboard
{
public string Description { get; set; }
public string DeviceID { get; set; }
}
I tried something like that for my treeview, i'm binding data in Mainwindow like this :
DeviceTree.ItemsSource = deviceInfos;
MainWindow.xaml :
<TreeView Margin="10" BorderThickness="2" BorderBrush="Black" Name="DeviceTree">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="x:Type data:DeviceInfo" ItemsSource="{Binding Keyboards}">
<TextBlock Text="{Binding Description}"></TextBlock>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="x:Type data:DeviceInfo" ItemsSource="{Binding OS}">
<TextBlock Text="{Binding Version}"></TextBlock>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="x:Type data:DeviceInfo" ItemsSource="{Binding VideoCard}">
<TextBlock Text="{Binding SerialNumber}"></TextBlock>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Actually It look like this in my treeview template:
"Model.DeviceInfo"
Every link of similar examples will be helpful for me. Thanks in advance
A
HierarchicalDataTemplatesupports only a single child property. It makes no sense to define three templates for the same type. Only of them can be applied at runtime anyway.What you should do is to transform your
DeviceInfoclass into a data-binding friendly view model class that has a single child property:You would then bind the
ItemsSourceproperty to anIEnumerable<Item>of fourItemroot objects, i.e. the level 1 keyboard, OS, CPU and VideoCard nodes.Also note the sytax for setting the
DataTypeproperty to an actual type in XAML:Edit:
If the total number of levels is not dynamic, i.e. you always have a total of two levels, you could set or bind the
ItemsSourceproperty to anew List<DeviceInfo>(1) { deviceInfos }and add the "static" root levels to theTreeViewexplicitly in your XAML markup: