Search code examples
wpfuser-controlstreeviewobservablecollectiondependency-properties

Binding an ObservableCollection Dependency Property in a User Control


I have a UserControl that hosts a TreeView that has a custom collection which inherits from ObservableCollection of a custom class. I am trying to bind to a property using a dependency property from a ViewModel, whilst I have proven the process works for another property it does not work here.

I'm sure it is something silly I have missed but I've been going round in circles, can anyone spot my mistake?

The UserControl XAML:

<UserControl
x:Class="FileExplorer.TreeViewUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:fe="clr-namespace:WpfControlLibrary.FileExplorer"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="FileExplorer"
d:DesignHeight="300"
d:DesignWidth="400"
mc:Ignorable="d">
<TreeView
    BorderThickness="0"
    ItemsSource="{Binding FileSystem, RelativeSource={RelativeSource AncestorType=UserControl}}"
    TreeViewItem.Collapsed="TreeView_Collapsed"
    TreeViewItem.Expanded="TreeView_Expanded"
    VirtualizingStackPanel.IsVirtualizing="True"
    VirtualizingStackPanel.VirtualizationMode="Recycling">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type fe:FileSystemObject}" ItemsSource="{Binding Items}">
            <StackPanel Margin="0,2" Orientation="Horizontal">
                <Image
                    Width="14"
                    Margin="2"
                    Source="{Binding Image}"
                    Stretch="Fill" />
                <TextBlock
                    VerticalAlignment="Center"
                    FontSize="{StaticResource FontSizeSmall}"
                    Text="{Binding Name}" />
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

The code behind for the UserControl:

    Namespace FileExplorer
    Public Class TreeViewUserControl
        Inherits UserControl

#Region "Constructors"
        Public Sub New()

            ' This call is required by the designer.
            InitializeComponent()

            ' Add any initialization after the InitializeComponent() call.
            Me.DataContext = Me
        End Sub

#End Region

#Region "Properties"

        Public Shared ReadOnly FileSystemProperty As DependencyProperty = DependencyProperty.Register("FileSystem", GetType(FileSystemObjectCollection), GetType(TreeViewUserControl))

        Public Property FileSystem As FileSystemObjectCollection
            Get
                Return CType(GetValue(FileSystemProperty), FileSystemObjectCollection)
            End Get
            Set(ByVal value As FileSystemObjectCollection)
                SetValue(FileSystemProperty, value)
                FileExplorer.UpdateLayout()
            End Set
        End Property

#End Region

   Private Function GetFileSystemInfo(ByVal root As String) As FileSystemObjectCollection
        Dim items As New FileSystemObjectCollection

        ' Parse all the directories at the path
        For Each dir As String In Directory.GetDirectories(root)
            items.Add(New FileSystemObject(dir, root))
        Next

        ' Parse all the file at the path
        For Each file As String In Directory.GetFiles(root)
            items.Add(New FileSystemObject(file, root))
        Next

        Return items
    End Function

    Private Sub TreeView_Collapsed(sender As Object, e As RoutedEventArgs)
        Dim node As TreeViewItem = CType(e.OriginalSource, TreeViewItem)
        Dim fs As FileSystemObject = CType(node.DataContext, FileSystemObject)
        fs.Clear()
    End Sub

    Private Sub TreeView_Expanded(sender As Object, e As RoutedEventArgs)
        Dim node As TreeViewItem = CType(e.OriginalSource, TreeViewItem)
        Dim fs As FileSystemObject = CType(node.DataContext, FileSystemObject)
        If Not fs.HasChildren Then Exit Sub
        fs.Items = GetFileSystemInfo(fs.FullName)
    End Sub

    End Class

End Namespace

The MainWindow XAML:

<Window
    x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:fe="clr-namespace:WpfControlLibrary.FileExplorer;assembly=WpfControlLibrary"
    xmlns:local="clr-namespace:ModStudio.Client"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:vm="clr-namespace:ModStudio.Client.ViewModels"
    Title="MainWindow"
    d:DesignHeight="600"
    d:DesignWidth="800"
    WindowStartupLocation="CenterOwner"
    WindowState="Maximized"
    mc:Ignorable="d">

    <Window.Resources>
        <vm:MainWindowViewModel x:Key="MainWindowViewModel" />
    </Window.Resources>

    <Grid>
        <fe:TreeViewUserControl DataContext="{StaticResource MainWindowViewModel}" FileSystem="{Binding ApplicationExplorer}" />
    </Grid>
</Window>

The MainWindow has its DataContext set to a new instance of the ViewModel in code behind. The MainWindowViewModel has a property called ApplicationExplorer which is an instance of FileSystemObjectCollection. As mentioned FileSystemObjectCollection inherits from ObservableCollection(Of FileSystemObject). A FileSystemObject implements INotifyPropertyChanged. If I change ApplicationExplorer property, the control remains blank.

I have intentionally omitted some code here, but can add them if necessary.


Solution

  • Don't set the DataContext in the UserControl, i.e. remove this line:

    Me.DataContext = Me
    

    When you explcitly set the DataContext like this, you break the inheritance chain which means that the binding to the ApplicationExplorer property in your window no longer works:

    <fe:TreeViewUserControl DataContext="{StaticResource MainWindowViewModel}" 
                            FileSystem="{Binding ApplicationExplorer}" />