wpf - 为 WPF 设计数据模板

标签 wpf visual-studio-2008 xaml

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

最佳答案

您可以在设计时通过 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" });
        }
    }
    

    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>
    

    关于wpf - 为 WPF 设计数据模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/998197/

    相关文章:

    asp.net - 在使用 Windows Auth 的 Windows 7 上使用 VS 2008 的调试 Web 服务器时,User.IsInRole 失败

    wpf - 为什么要在xaml,WPF的样式中定义模板?

    c# - 如何在 WPF 中的 Xaml 文件中添加注释?

    c++ - VS2008编译mshtml.h编译报错

    c# - WPF 是开发业务线用户界面的不错选择吗?

    c# - 将属性绑定(bind)到整数

    wpf - 文本框到数字绑定(bind)

    c# - Windows Mobile 6.5 构建时间 (VS2008)

    c# - 单击按钮上的 Xamarin.Forms 动画(Flash 背景)

    c# - WPF:如何以编程方式从 ScrollViewer 中提取滚动条?