Question

So, in a few words. I have a structure of classes, each contains List with "child" items of another class. I need to bind it to the TreeView with custom Template for every class.

The main class looks like this plus some properties and metods:

  public static class TreeVM
  {
    public string Name { get; set; }
    public static List<ConfigVM> configsVM = new List<ConfigVM>();
  }

This contains a List of ConfigVM items:

  public class ConfigVM
  {
    public string Name { get; set; }
    public List<ComPortVM> comPortsVM = new List<ComPortVM>();
  }

The same with class ComPortVM, etc.

I need to display it with TreeView. I wrote some xaml-code to define the view of each class:

    <HierarchicalDataTemplate DataType="{x:Type vm:TreeVM}" ItemsSource="{Binding configsVM}">
      <StackPanel Orientation="Horizontal">
        <RadioButton Height="16" GroupName="Config" VerticalAlignment="Center" HorizontalAlignment="Left"/>
        <Image Source="Icons/IconConfig.png"/>
        <TextBlock Text="{Binding Name}" />
      </StackPanel>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="{x:Type vm:ConfigVM}" ItemsSource="{Binding _comPortsVM}">
      <StackPanel Orientation="Horizontal">
        <CheckBox Height="16" VerticalAlignment="Center" HorizontalAlignment="Left"/>
        <Image Source="Icons/IconComPort.png"/>
        <TextBlock Text="{Binding Name}" />
      </StackPanel>
    </HierarchicalDataTemplate>

And TreeView:

    <Grid x:Name="GridForTreeView" DataContext="{Binding vm:TreeVM}">
      <TreeView x:Name="ComPortsTree"
                ItemsSource="{Binding}" />
    </Grid>

But it doesn't work.

How to make it right?

Was it helpful?

Solution

Try to replace

 public static List<ConfigVM> configsVM = new List<ConfigVM>();

for

 public List<ConfigVM> configsVM {get;set}

Then initialize your list in the contructor

public TreeVM (){ configsVM = new List<ConfigVM> ();}

Do the same for the other class.

Then in your XAML try to do this:

 <Grid x:Name="GridForTreeView" DataContext="{Binding vm:TreeVM}">
      <TreeView x:Name="ComPortsTree"
                ItemsSource="{Binding configsVM }" ItemTemplate= {StaticResource hierachTemplate} />
    </Grid>

and in your hierarchical:

<HierarchicalDataTemplate x:Name="hierachTemplate" ItemsSource="{Binding comPortsVM }">

Guess that's it...give it a try

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top