设计时的ItemsSource在ItemsControl上

13

我正在尝试设计我的ItemsControlDataTemplate,我需要一些模拟数据来填充模板。我阅读到使用d:DataContext就足够了,这样我就不必创建一个模拟类。我该怎么做?

1个回答

14

你必须在XAML中声明使用d:DataContext的实例,例如可以使用StaticResource。以下是一种实现方式:

<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>

我所使用的数据上下文类定义如下:

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") };
            }
        }
    }
}

当然,你也可以在UserControl或你的窗口上设置数据上下文。

这是结果:enter image description here


5
我读到将其作为资源加载会使应用程序在运行时也加载它。我正在使用 d:DataContext="{d:DesignInstance Type=mocks:MyViewModelMock, IsDesignTimeCreatable=True},但它不起作用。 - Christopher Francisco
1
@ChristopherFrancisco 使用d:DesignInstance也可以。尝试重新启动VS并重建解决方案。设计师有时会懒得更新... - helb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接