c# – 在ItemsControl上设计时间ItemsSource

前端之家收集整理的这篇文章主要介绍了c# – 在ItemsControl上设计时间ItemsSource前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试为我的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上设置数据上下文.

这是结果:

原文链接:https://www.f2er.com/csharp/243216.html

猜你在找的C#相关文章