tags:

views:

33

answers:

1

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?

A: 

Do this in code behind

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

and in xaml

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

Ideally you should follow MVVM design to isolated data from code behind

Rakesh Gunijan
OK. but i would prefer to write it in xaml like <Window.DataContext> <local:ViewModel/> </Window.DataContext>It is often a bit disappointing that sometimes I dont't need to explicitly set up DataContext while sometimes I must.
Kirill Lykov