如何查看我的数据绑定项ItemTemplate的设计?

Ben*_*ele 2 c# wpf visual-studio-2013

我有一个简单的ListBox绑定对象集合ItemsSource.我现在分配的DataTemplate非常简单,但我怎样才能在设计器中看到该模板?

这是我的xaml:

<ListBox.ItemTemplate>
    <DataTemplate>
        <Grid>
            <TextBlock Text="{Binding Title}" />
            <TextBlock Text="{Binding Address}" />
        </Grid>
    </DataTemplate>
</ListBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

这就是设计师的样子:

在此输入图像描述

这就是数据绑定和应用程序运行时的外观:

在此输入图像描述

如何让设计师展示我的预览DataTemplate?我不需要填写的实际数据(在运行时发生),但欣赏预览.

Mur*_*ven 6

您需要设计时数据.您可以使用d:DataContext属性声明设计时数据上下文.您可以创建模拟类,以便为设计人员在设计时显示模拟列表.

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        mc:Ignorable="d" 
        x:Class="WpfAnswer001.Window1"
        d:DataContext="{StaticResource ResourceKey=MockMasterViewModel}"
        Title="Window1" d:DesignWidth="523.5">
    <Grid>
        <ListBox ItemsSource="{Binding Path=Items}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="4">
                        <TextBlock Text="{Binding Title}" />
                        <TextBlock Text="{Binding Address}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

这是在App.xaml中声明模拟视图模型的方法:

<Application x:Class="WpfAnswer001.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfAnswer001"
             StartupUri="Window1.xaml">
    <Application.Resources>
        <local:MockMasterViewModel x:Key="MockMasterViewModel"/>
    </Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)

这是模拟视图模型的代码如下所示:

using System.Collections.ObjectModel;

public class MockItemViewModel
{
    public string Title { get; set; }
    public string Address { get; set; }
}

public class MockMasterViewModel
{

    public ObservableCollection<MockItemViewModel> Items { get; set; }

    public MockMasterViewModel()
    {
        var item01 = new MockItemViewModel() { Title = "Title 01", Address = "Address 01" };
        var item02 = new MockItemViewModel() { Title = "Title 02", Address = "Address 02" };
        Items = new ObservableCollection<MockItemViewModel>()
        {
            item01, item02
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

这是它在Visual Studio中的外观:

在此输入图像描述

值得努力和编码吗?这取决于你,但这是应该做的.

否则,请使用空白设计器并仅在运行时进行测试.

当您使用Expression Blend进行大量工作并且确实需要查看项目的外观时,这非常有用.