为WPF设计数据模板

Den*_*ail 4 wpf xaml visual-studio-2008

使用WPF,XAML,VS2008和Blend 2(或3 Beta首选),您创建数据模板的过程是什么?你是否有一个测试数据模板外观的过程而没有启动应用程序只是为了测试数据的外观?我是否可以在Blend中使用一个过程来使开发数据模板更具图形化?

geo*_*tnz 6

您可以通过Blend在设计时指定数据,或者(也可以在VS中使用它)执行以下操作:

  • 创建您设置为DataContext的对象的子类.
  • 在此子类的构造函数中,将属性设置为某些测试值.
  • 将子类的实例声明为资源.
  • 将DataContext设置为此资源.
  • 请记住在运行时清除或设置DataContext为合理的东西,否则用户将看到您的设计时数据.

也适用于Silverlight.

这是一些示例代码:

// 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" });
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)