Need Mock XAML data at design time
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.开发者_如何学JAVA 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?
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:
What's 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.
精彩评论