Search code examples
c#wpfdata-bindingdatacontext

How to pass Collection through DataContext to UserControl's ListBox?


I want to separate ListBox from MainMenu by creating UserControl. In MainWindow I'm creating, for testing purposes, ObservableCollection (in code-behind) and in MainWindow.xaml I'm trying to pass this Collection through DataContext to UserControl

MainWindow.xaml.cs

ObservableCollection<ListItem> coll = new ObservableCollection<ListItem>() 
{ 
    new TextListItem 
    {
        Content = "Some Text", CreationDate = DateTime.Now, VisibleName = "Title" 
    } 
};

MainWindow.xaml

<userControls:ListBoxUserControl DataContext="{Binding Path=coll}"/>

And in ListBoxUserControl.xaml I'm trying to access Collection like that

<ListBox x:Name="listBox" ItemsSource="{Binding}"/>

But it seems not working. How do I pass Collection through DataContext properly?


Solution

  • coll should be a property on the MainWindow class. As I currently read it, it is just a variable which will go out of scope after you left the method (I think the constructor) in which it is defined.