在ItemsControl上设计时间ItemsSource

时间:2015-01-17 21:32:40

标签: c# wpf datatemplate

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

1 个答案:

答案 0 :(得分:9)

必须在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

相关问题