Tech Off Post

Single Post Permalink

View Thread: Silverlight 4 : ItemSource vs DataContext
  • User profile image

    spivonious said:

    MVVM is a nice pattern for WPF/SL, but it has nothing to do with your question.


    Let's say I have an object, "myThingie" that has a couple collections inside of it, "Stuff", "Things", and "People".


    I have a form that has a Grid, "myGrid", with three ListBoxes, "lst1", "lst2", "lst3".


    Here's my XAML (with extraneous stuff removed):


    <Grid DataContext={StaticResource myThingie}>

    <ListBox ItemSource={Binding Stuff}/>

    <ListBox ItemSource={Binding Things}/>

    <ListBox ItemSource={Binding People}/>



    Because there's no source defined in the Binding statements, the ListBoxes automatically look to the DataContext. They'll go up the tree until they find one that's defined.


    Without the DataContext, the ItemSource binding statements get much more complex, and if I ever need to change the source of the data, I'd have to update all of them, instead of the one DataContext.


    Frankly, I'm surprised that just setting the ListBox DataContext works. I would have thought you'd need a ItemSource={Binding} for that to work.

    I see. Thanks for the clear help.


    I do have " ItemsSource="{Binding}"" in my XAML for the listBox1.


    A small question, "myThingies"... in my case, it's a ObservableCollection<T>, now, how can I have "Stuff","Things","People" in this? Do you mean 3 other ObservableCollection<T> inside that one with the name "Stuff","Things" and "People"?


    and if that is the case, so when I do the  ItemsSource="{Binding Stuff}" , it will automatically match it with it, right?


    What I mean is, I do understand what you said but I am unsure how I can have several collections in "one" and then attach it to the datacontext? Could you give me a small sample code on an observablecollection having "3" stuff in it?