我有一个简单的ListBox
,并将对象集合绑定为ItemsSource
。
我现在分配的DataTemplate非常简单,但我怎样才能在设计器中看到该模板?
这是我的xaml:
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Title}" />
<TextBlock Text="{Binding Address}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
这就是设计师的样子:
这就是数据绑定和应用程序运行时的外观:
如何让设计师显示我DataTemplate
的预览?
我不需要填写的实际数据(在运行时发生),但我们非常感谢预览。
答案 0 :(得分:5)
您需要设计时数据。您可以使用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>
这是在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>
这就是模拟视图模型的代码:
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
};
}
}
它在Visual Studio中的外观如下:
值得努力和编码吗?这取决于你,但这是应该做的。
否则,请使用空白设计器并仅在运行时进行测试。
当您使用Expression Blend进行大量工作并且确实需要查看项目的外观时,这非常有用。