0

I am trying to bind an ObservableCollection of custom type to a TreeView.

The custom ErrorDetails class looks like this:

class ErrorDetail
{
    public string Error;
    public List<String> FilesList;
}

In my ViewModel, I populate the collection using below linq query. The errorCollection is part of the DataContext.

var results = (from p in Transactions
    group p.FileName by p.Error.ToString()
    into g
    select new ErrorDetail() {Error = g.Key, FilesList = g.ToList()}).ToList();

errorCollection = new ObservableCollection<ErrorDetail>(results);

On the TreeView, I want to show each error and its associated files as its child nodes.

Below is my XAML

<Grid Name="ErrorView" Margin="10">
    <TreeView ItemsSource="{Binding Path=ErrorModel.ErrorDetails}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=FilesList}">
                <TextBlock Foreground="Red" Text="{Binding Path=Error}" />
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=FilesList}" />
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid>

I'm doubtful about the Binding in the 2nd TextBlock . Regardless, I tried multiple combinations but nothing shows up.

Please guide.

Edit: Adding more to the end result, The collection populates correctly but nothing shows up on the TreeView.

2 Answers2

0
  <TreeView ItemsSource="{Binding  ErrorList}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=FilesList}">
                <TextBlock Foreground="Red"
                           Text="{Binding Path=Error}" />
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" />
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

enter image description here

zhaojingbo
  • 131
  • 6
0

While zhaojingbo's answer was spot on, I realized one basic thing I was missing was to have properties in the ErrorDetail class, instead of just public fields.

Didn't realize WPF was so strict about requiring properties.