tags:

views:

213

answers:

2

I'm using a static array of objects defined in XAML as my ItemsSource on a list box.

I use:

ItemsSource="{Binding Source={StaticResource theSource}}".

This works great at design time. However, I need to override this at run time so the list box will take it's items from a collection property on my view model. I exposed a Property Named "theSource" and set the Window DataContext in code behind. However, the list is still bound to the static resource... not to the property on my view model.

Any suggestion on the right way to have Design Time data for visualizing the UI and replace with live data at run time?

A: 

Just name your Listbox control

<ListBox x:Name="myListBox" 
 ItemsSource="{Binding Source={StaticResource theSource}}" />

and change it at runtime

myListBox.ItemsSource = datasource;


Second take at this problem:

http://stackoverflow.com/questions/200839/whats-the-difference-between-staticresource-and-dynamicresource-in-wpf

If you're using WPF, then you might use a DynamicResource instead, and change the definition of this at runtime

It will fail with Silverlight, though, because this lighter framework doesn't support dynamic resources.


Third take

Since you want to use a binding to your controller object, then :

<Page xmlns="http://..." xmlns:your="...">
<Page.DataContext>
  <your:DesignTimeObject> <!-- Must be of the same type as in runtime, or at least expose properties and subproperties with the same name -->
   <your:DesignTimeObject.List>
 <your:Element id="1" />
  <your:Element id="2" />
  <!-- snip -->
   <your:DesignTimeObject.List>
  </your:DesignTimeObject>
</Page.DataContext>
<ListBox x:Name="myListBox"  ItemsSource="{Binding List}" /> <!-- Binds to the Element list with id="1" , id="2" ... -->
</Page>

With this way, you don't have to change your binding at runtime, set the DataContext once and be done with it.

Johan Buret
Yes, I suppose that would work but I'm trying to follow the model-view-viewmodel principles.So, I'd like to just set the window data context and let WPF binding resolve to the runtime data. Thanks for the suggestion though.
thrag
Your third take definitely put me on the right track. I used a slight variation to declare the DataContext as an array of my CLR object and the ItemSource={Binding }This does exactly what I needed.Thanks.
thrag