C# 项目控件上的设计时项目资源
我正在尝试为我的C# 项目控件上的设计时项目资源,c#,wpf,datatemplate,C#,Wpf,Datatemplate,我正在尝试为我的ItemsControl设计DataTemplate,我需要一些模拟数据来填充模板。我使用d:DataContext阅读已经足够了,因此我不必创建模拟类。如何才能做到这一点?必须在XAML中声明必须与d:DataContext一起使用的实例,例如使用StaticResource 以下是您如何做到这一点: <UserControl x:Class="WpfApplication1.UserControl1" xmlns:local="clr-name
ItemsControl
设计DataTemplate
,我需要一些模拟数据来填充模板。我使用d:DataContext
阅读已经足够了,因此我不必创建模拟类。如何才能做到这一点?必须在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>
用作数据上下文的类I定义如下:
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") };
}
}
}
}
命名空间WpfApplication1
{
公共类项目
{
公共项(字符串名称)
{
名称=名称;
}
公共字符串名称{get;private set;}
}
公共类MyViewModel
{
公共清单项目
{
得到
{
返回新列表(){new Item(“Thing 1”)、new Item(“Thing 2”)};
}
}
}
}
当然,您也可以在UserControl
或窗口上设置数据上下文
结果如下:
我了解到,将其作为资源加载将使应用程序在运行时也加载它。我使用的是
d:DataContext=“{d:DesignInstance Type=mocks:MyViewModelMock,isdesigntimecreateable=True}
,但它没有work@ChristopherFrancisco使用d:DesignInstance也可以。尝试重新启动VS并重建解决方案。设计器有时在更新时有点懒惰。。。