Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding ObservableCollection to WPF ListBox

I have the below code-behind:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        ObservableCollection<int> sampleData = new ObservableCollection<int>();
        public ObservableCollection<int> SampleData
        {
            get
            {
                if (sampleData.Count <= 0)
                {
                    sampleData.Add(1);
                    sampleData.Add(2);
                    sampleData.Add(3);
                    sampleData.Add(4);
                }
                return sampleData;
            }
        }
    }

My xaml is:

<Window x:Class="Sandbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding Path=SampleData}"/>
    </Grid>
</Window>

The list doesn't display the values in the collection (or anything at all). Can someone point out what my mistake is?

Do I need to set the DataContext explicitly? I thought if none is set the control will just use itself as the DataContext.

like image 332
Flack Avatar asked Nov 09 '10 21:11

Flack


1 Answers

Yes, you'll need to set the DataContext somehow. It doesn't have a DataContext, because the Window doesn't have a DataContext unless it is set. The ListBox will get the DataContext if you do this in the constructor.

public MainWindow() 
{ 
    InitializeComponent(); 
    this.DataContext = this;
} 

Otherwise you can use RelativeSource, ElementName etc. in the Binding but I guess you knew that =)

like image 149
Fredrik Hedblad Avatar answered Nov 07 '22 22:11

Fredrik Hedblad