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 know that the question lacked a direct reference to the pattern but he inevitably will start to get his "knickers in a twist" if he does not start using it.