[英]Design time ItemsSource on ItemsControl
I'm trying to design the DataTemplate
for my ItemsControl
and I need some mock data to populate the template. 我正在尝试为我的ItemsControl
设计DataTemplate
,我需要一些模拟数据来填充模板。 I read using d:DataContext
is enough so that I don't have to create a mock class. 我用d:DataContext
读取d:DataContext
就足够了,所以我不必创建一个mock类。 How can I do this? 我怎样才能做到这一点?
The instance you have to use with d:DataContext must be declared in the XAML, with a StaticResource
for example. 必须在XAML中声明必须与d:DataContext一起使用的实例,例如使用StaticResource
。
Here is how you could do it: 您可以这样做:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns:local="clr-namespace:WpfApplication1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<local:MyViewModel x:Key="mockViewModel"/>
</UserControl.Resources>
<Grid>
<ItemsControl d:DataContext="{StaticResource mockViewModel}"
ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</UserControl>
The class I used as data context is defined as follows: 我用作数据上下文的类定义如下:
namespace WpfApplication1
{
public class Item
{
public Item(string name)
{
Name = name;
}
public string Name { get; private set; }
}
public class MyViewModel
{
public List<Item> Items
{
get
{
return new List<Item>() { new Item("Thing 1"), new Item("Thing 2") };
}
}
}
}
Of course, you can also set the data context on the UserControl
or on your Window. 当然,您也可以在UserControl
或Window上设置数据上下文。
Here's the result: 这是结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.