ListBox.ItemsSource binding in code and in xaml

Kirill Lykov picture Kirill Lykov · Sep 2, 2010 · Viewed 23.8k times · Source

I wrote simple code like

public ObservableCollection<string> Names …
public Window1()
{
    PutInDataIntoNames();
    InitializeComponent();
    this.listBox1.ItemsSource = Names;
}

and in xaml

<Grid>
    <ListBox Margin="10,11,10,16"
         Name="listBox1"
         Background="Black" 
         Foreground="Orange" 
         />
</Grid>

Then I wanted to set ItemsSource property in xaml. In order to do that I wrote the following:

ItemsSource="{Binding Path=Names}"

Unfortunately, it doesn’t work. Could you explain why and how to do that right?

Answer

H.B. picture H.B. · Apr 1, 2011

If you only specify the binding path the binding engine will try to navigate the path starting from the current DataContext so ItemsSource="{Binding Path=Names}" does not work like this, there are a lot of different things to keep in mind especially when doing more complex things.

The single most important article that everyone who is new to DataBinding should read is the Data Binding Overview on MSDN

To get back to your binding, if you want to do it completely in XAML you can do that as well, you just need to make the Window your source somehow, either by referencing it directly or relatively or by setting it up as the DataContext.

1 - Direct Reference:

<Window Name="Window"
        ...>
    <Grid> 
            <ListBox ...
                     ItemsSource="{Binding ElementName=Window, Path=Names}"
                     .../>
    </Grid>
</Window>

2 - Relative Reference

    <Grid> 
            <ListBox ...
                     ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Names}"
                     .../>
    </Grid>

3 - Setting up the DataContext

<Window ...
        DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
    <Grid> 
            <ListBox ...
                     ItemsSource="{Binding Path=Names}"
                     .../>
    </Grid>
</Window>