加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在ItemsControl上设计时间ItemsSource

发布时间:2020-12-15 08:20:18 所属栏目:百科 来源:网络整理
导读:我正在尝试为我的ItemsControl设计DataTemplate,我需要一些模拟数据来填充模板.我用d读取:DataContext就足够了,所以我不必创建一个mock类.我怎样才能做到这一点? 解决方法 必须在XAML中声明必须与d:DataContext一起使用的实例,例如使用StaticResource. 您
我正在尝试为我的ItemsControl设计DataTemplate,我需要一些模拟数据来填充模板.我用d读取:DataContext就足够了,所以我不必创建一个mock类.我怎样才能做到这一点?

解决方法

必须在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或Window上设置数据上下文.

这是结果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读