wpf中的设计数据
本文关键字:数据 wpf | 更新日期: 2023-09-27 18:21:20
我有一个用户控件和视图模型,它存在一个属性Reports。usercontrol的数据上下文绑定到视图模型。
在控件中,我有一个列表框,该列表框绑定到属性Reports
<ListBox x:Name="ReportListBox" ItemsSource="{Binding Reports}"
ItemTemplate="{StaticResource reportItemTemplate}"
IsSynchronizedWithCurrentItem="True"
Visibility="Visible" SelectionMode="Single">
</ListBox>
我想要的是有一些设计数据,所以我创建了一个像这样的xaml文件。
<m:Reports xmlns:m="clr-namespace:MYAPP.Modules.ReportList.Models">
<m:Report ReportName="Reportname 1" Id="AAAA-BBB-CCC" ></m:Report>
<m:Report ReportName="Reportname 2" Id="AAAA-BBB-CCC" ></m:Report>
</m:Reports>
如果我真的喜欢这样,VS设计中就不会显示任何内容。如果我将列表框的绑定更改为
<ListBox x:Name="ReportListBox" ItemsSource="{Binding}"
我能看到设计的价值。我意识到为什么会出现这种情况,因为用户控件在运行时绑定到视图模型。我想我需要的设计数据是这样的
<mc:ReportListViewModel xmlns:mc="clr-namespace:MYAPP.Modules.ReportList.ViewModels">
<m:Reports xmlns:m="clr-namespace:MYAPP.Modules.ReportList.Models">
<m:Report ReportName="Reportname 1" Id="AAAA-BBB-CCC" ></m:Report>
<m:Report ReportName="Reportname 2" Id="AAAA-BBB-CCC" ></m:Report>
</m:Reports>
</mc:ReportListViewModel>
</m:Reports>
但我弄错了。"类型'ReportListViewModel'不支持直接内容"。任何人都有一个解决方案
获取设计时数据的一种方法是在代码中创建两个视图模型。一种是普通的运行时视图模型。第二个可以用伪数据截取。然后,在xaml中,您可以在设计器中通过设置以混合命名空间为前缀的Datacontext来选择性地设置数据上下文
<Page
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d:DataContext="{StaticResource DummyViewModel}">
然后在资源中创建对象的实例
<Page.Resources>
<local:DummyViewModelClass x:Key="DummyViewModel">
</Page.Resources>
这是一个快速原型设计的简单解决方案,但可能不一定能很好地扩展。
另一种选择是在代码中识别您处于设计模式,并通过使用添加到类中的一些辅助方法来更改视图模型的填充方式。以下是该方法的一个示例。
http://blogs.msdn.com/b/delay/archive/2009/02/26/designerproperties-getisindesignmode-forrealz-how-to-reliably-detect-silverlight-design-mode-in-blend-and-visual-studio.aspx