Using WPF, XAML, VS2008, and Blend 2 (or 3 Beta preferred), what is your process for creating data templates? Do you have a process for testing the data template's appearance WITHOUT spinning up your app just to test how the data looks? Is there a process I can use in Blend to make developing data templates more graphical?
+4
A:
You can specify data at design-time through Blend, or (to get it working in VS as well) do this:
- Create a subclass of the object that you set as your DataContext.
- In the constructor of this subclass, set the properties to some test values.
- Declare an instance of the subclass as a resource.
- Set the DataContext to this resource.
- Remember to clear or set the DataContext to something sensible at runtime, otherwise users will see your design-time data.
Works in Silverlight as well.
Here's some example 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>
geofftnz
2009-06-15 20:30:43