在xaml中设计datatemplate的时间数据

MTR*_*MTR 12 wpf xaml datatemplate designview

这可能是一个愚蠢的问题,但是可以将一些示例数据定义为DataContext,以便在DesignView中查看我的DataTemplate吗?

目前,我总是要运行我的应用程序,看看我的更改是否正常.

例如,使用以下代码,DesignView只显示一个空列表框:

 <ListBox x:Name="standardLayoutListBox" ItemsSource="{Binding myListboxItems}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Label Grid.Column="0" Content="{Binding text1}" />
                <Label Grid.Column="1" Content="{Binding text2}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

Joe*_*uso 16

public class MyMockClass
{
    public MyMockClass()
    {
        MyListBoxItems.Add(new MyDataClass() { text1 = "test text 1", text2 = "test text 2" });
        MyListBoxItems.Add(new MyDataClass() { text1 = "test text 3", text2 = "test text 4" });
    }
    public ObservableCollection<MyDataClass> MyListBoxItems { get; set; }
}

public class MyDataClass
{
    public string text1 { get; set; }
    public string text2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在你的XAML中

添加名称空间声明

 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Run Code Online (Sandbox Code Playgroud)

将模拟数据上下文添加到窗口/控件资源

<UserControl.Resources> 
    <local:MyMockClass x:Key="DesignViewModel"/> 
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)

然后修改ListBox以引用设计时对象

<ListBox x:Name="standardLayoutListBox" 
 d:DataContext="{Binding Source={StaticResource DesignViewModel}}"
ItemsSource="{Binding MyListBoxItems}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Label Grid.Column="0" Content="{Binding text1}" />
                <Label Grid.Column="1" Content="{Binding text2}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

  • 添加myListBoxItems = new后,ObservableCollection <MyDataClass>(); 到MyMockClass的构造函数没有错误消息,但Listbox仍然是空的. (3认同)
  • 不要忘记在命名空间声明中设置mc:Ignorable:xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable ="d" (2认同)
  • 本地资源定义可以排除在外,如果引用的DataContext类型这样的设计:d:DataContext的="{d:DesignInstance IsDesignTimeCreatable =真,类型=本地:MyMockData}" (2认同)