Search code examples
wpflistboxitemssource

ListBox.ItemsSource binding in code and in xaml


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?


Solution

  • Do this in code behind

    public Window1() 
    { 
        PutInDataIntoNames(); 
        InitializeComponent(); 
        DataContext = this;
    } 
    

    and in XAML

    <Grid> 
        <ListBox ItemsSource="{Binding Names}"
             Margin="10,11,10,16" 
             Name="listBox1" 
             Background="Black"  
             Foreground="Orange"   
             /> 
    </Grid>
    

    Ideally you should follow MVVM design to isolate data from code behind.