You can specify data at design time through Blend or (to make it work in VS as well):
- Subclass the object that you set as the DataContext.
- In the constructor of this subclass, set properties for some test values.
- Declare an instance of a subclass as a resource.
- Set the DataContext for this resource.
- Remember to clear or set the DataContext to something reasonable at runtime, otherwise users will see your development time data.
Also works in Silverlight.
Here is a sample code:
// The object (in a list) that'll be bound as our ListBox ItemsSource public class Person { public string FirstName { get; set; } public string LastName { get; set; } } // Our design-time data. Note that we add list items in the constructor public class PersonDesignTimeData : ObservableCollection<Person> { public PersonDesignTimeData() { this.Add(new Person { FirstName = "Fred", LastName = "Smith" }); this.Add(new Person { FirstName = "Jim", LastName = "Brown" }); this.Add(new Person { FirstName = "Dave", LastName = "Jones" }); } }
Window1.xaml:
<Window x:Class="DesignTimeDataDemo.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DesignTimeDataDemo" Title="Window1" Height="300" Width="300"> <Window.Resources> <local:PersonDesignTimeData x:Key="PersonDesignTimeData"/> </Window.Resources> <Grid x:Name="root" DataContext="{StaticResource PersonDesignTimeData}"> <ListBox ItemsSource="{Binding}" > <ListBox.ItemTemplate> <DataTemplate> <Grid Width="200"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="2*"/> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="{Binding FirstName}"/> <TextBlock Grid.Column="1" Text="{Binding LastName}"/> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window>
source share