我想知道如何使用CollectionViewSource在Expression Blend中显示设计时间数据,该数据位于SampleData.xaml中?在更改我的代码以使用CVS之前,我使用了一个ObservableCollection.我需要对其中的项进行过滤和排序,因此我更改了代码以使用CVS.现在,我的设计师抱怨无法使用适当的结构填充SampleData的NextItems以显示在Expression Blend中.这是我在app中使用的一些代码:
Mainviewmodel.cs
class Mainviewmodel { public Mainviewmodel() { AllItems = new ObservableCollection<Itemviewmodel>(); NextItems = new CollectionViewSource(); NextItems.Source = AllItems; } public CollectionViewSource NextItems { get; private set; } public ObservableCollection<Itemviewmodel> AllItems { get; private set; } some functions to fill,filter,sort etc... }
MainView.xaml:
<phone:PhoneApplicationPage ... some other stuff ... d:DesignWidth="480" d:DesignHeight="728" d:DataContext="{d:DesignData SampleData/SampleData.xaml}"> <Grid x:Name="LayoutRoot" Background="Transparent"> <controls:Panorama> <controls:PanoramaItem> <ListBox ItemsSource="{Binding NextItems.View}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <Image Source="{Binding Image}" /> <StackPanel> <TextBlock Text="{Binding FullName}" /> </StackPanel> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </controls:PanoramaItem> </controls:Panorama> </Grid> </phone:PhoneApplicationPage>
SampleData.xaml
<local:Mainviewmodel xmlns:local="clr-namespace:MyAppNamespace" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:swd="clr-namespace:System.Windows.Data;assembly=System.Windows" > <local:Mainviewmodel.AllItems> <local:ItemModel FullName="Dummy" Image="/Images/dummy.png" /> </local:Mainviewmodel.AllItems> <local:Mainviewmodel.NextItems> How to fill the CollectionViewSource's Source? </local:Mainviewmodel.NextItems> </local:Mainviewmodel>
所以我找不到答案的问题是如何在SampleDate.xaml中填充NextItems的Source?任何帮助将非常感激.
解决方法
如果你想在设计器中显示样本数据,我建议你从代码中进行.有两种方法可以为Blend Designer或VStudio设计器生成样本数据:
>像你一样从XML文件.
>来自c#类 – >最好的选择
最好的选择.
在WPF中,在Windows 8以及WP7.5和更高版本中,您可以访问一个名为:Windows.ApplicationModel.DesignMode.DesignModeEnabled的属性,利用它可以从视图模型中为您的ObservableCollection设定种子:
public class Mainviewmodel { public Mainviewmodel() { AllItems = new ObservableCollection<Itemviewmodel>(); if (DesignMode.DesignModeEnabled) { AllItems = FakeDataProvider.FakeDataItems; } NextItems.Source = AllItems; } public CollectionViewSource NextItems { get; private set; } public ObservableCollection<Itemviewmodel> AllItems { get; private set; } }
通过这种方式,如果您更改模型,则不必重新生成XML文件,从C#文件中可以更清晰一些. FakeDataProvider是一个静态类,其中存储了所有设计时伪造数据.因此,在XAML中,您唯一需要做的就是将ListBox绑定到viewmodel的集合.