-1

I am new to WPF a trying to do simple data binding with Treeview. I have ObservableCollection treeViewItems with one item and I want to display it with TreeView but I am struggling with the binding in XAML. Here is my code: C#

 public partial class MainWindow : Window
    {
        public ObservableCollection<FileItem> treeViewItems = new ObservableCollection<FileItem>
        {
            new FileItem
            {
                Name = "sdfsdfs",
            }
        };

        public MainWindow()
        {
            InitializeComponent();
        }


    }
    public class FileItem
    {
        public string Name { get; set; }
    }

XAML

        <TreeView x:Name="FilesTreeview" ItemsSource="{Binding Path=treeViewItems}">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="{x:Type local:FileItem}">
                    <TextBlock Text="{Binding Name}"/>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
Jakub
  • 95
  • 13
  • Check the output window when you have trouble with bindings, it will tell you about binding errors. – H.B. Jun 24 '20 at 13:51

1 Answers1

1

treeViewItems is a field, you cannot bind to fields, you need a public property, so e.g.

public ObservableCollection<FileItem> treeViewItems { get; } = ...

(The naming convention would also prefer the name TreeViewItems)

H.B.
  • 166,899
  • 29
  • 327
  • 400