Binding ListBox.ItemsSource 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 the ItemsSource property in xaml. For this, I wrote the following:

ItemsSource="{Binding Path=Names}"

Unfortunately, it does not work. Could you explain why and how to do this?

+5
source share
3 answers

Do it in code

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 the MVVM design to isolate data from code.

+3
source

If you specify only the binding path, the binding mechanism will try to move along the path starting from the current one DataContext, therefore it ItemsSource="{Binding Path=Names}"doesn’t work that way, there are many different things to keep in mind, especially when doing more complex things.

, , DataBinding, - MSDN.

, XAML, , Window - , , DataContext.

1 - :

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

2 -

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

3 - DataContext

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

It seems yours Namesmight be a field. You can ONLY bind to public properties

+3
source

All Articles