1

我用来在设计器d:DesignInstance中获取设计时数据。我的模型看起来像这样(简化):

interface IModel {
  public ObservableCollection<IConversation> OpenConversations { get; }
}

enum ConversationType {
  Channel, IM
}

interface IConversation {
  public string Name { get; }
  public ConversationType ConversationType { get; }
}

然后我有一个在OpenConversations属性中有几个条目的模拟模型。当用作ItemsSource我的ListView. 我的简化 XAML 视图如下所示:

<Page d:DataContext="{d:DesignInstance Type=mocks:MockModel, IsDesignTimeCreatable=True}">
  <ListView ItemsSource="{Binding OpenConversations}"/>
</Page>

上面的示例按预期工作,我得到了设计时数据。

但是现在我想在我的ListView使用中添加分组,CollectionViewSource所以我在我的 XAML 中添加了以下内容:

<Page.Resources>
  <CollectionViewSource x:Name="OpenConversations" IsSourceGrouped="True" />
</Page.Resources>

并将其更改ListView为:

<ListView ItemSource="{StaticResource OpenConversations}" />

我无法真正弄清楚的是如何将设计数据放入 中 CollectionViewSource,我尝试了以下方法,但它不起作用:

<CollectionViewSource ... Source="{Binding OpenConversations}" />

根据https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh780627.aspx上的文档,我需要(在代码隐藏中)分配CollectionViewSource.Source = from conversation in OpenConversations group by conversation.ConversationType into group select group。但我无法弄清楚如何使用设计时数据来做到这一点。

4

1 回答 1

0

首先尝试定义一个组的外观我的意思是组的标题,还有更多

public class  Group<T> : ObservableCollection<T>, INotifyPropertyChanged
{
  public Group(string name,IEnumerable<T> items):base(items)
   { Name=name;
   }
  //more ...
}

这个类不仅仅是静态数据,它处理变化的数据。现在,如果您使用 MVVM 模型在您的 viewmodel(home) 中定义一个新 ObservableCollection> PS 类型的属性 ListGroup (命名您想要的名称), 这不是真正的代码,只是提供一个想法的模型。

 var s = from val in OpenConversations 
         group val by val.Conversationb into g 
         select new Group<IConversation>(g.Key.ToString(), g);
 GroupList = new ObservableCollection<Group<IConversation>>(s);

现在像在资源中的 CollectionViewSource 之前一样创建一个

    <CollectionViewSource x:Key="cvs" IsSourceGrouped="True" Source="{Binding Source={StaticResource home},Path=GroupList}"/>

      <ListView ItemsSource="{Binding Source={StaticResource cvs}}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Background="Salmon" Width="100" Height="100">
                    <TextBlock  Text="{Binding Name}"/>
                </StackPanel>
            </DataTemplate>              
        </ListView.ItemTemplate>
        <ListView.GroupStyle>
            <GroupStyle >
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <Grid Background="LightGray"  >
                            <TextBlock Text='{Binding Name}' Foreground="Black" Margin="10"
                           Style="{StaticResource SubheaderTextBlockStyle}" />
                        </Grid>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListView.GroupStyle>               
    </ListView>

看看如何定义 GroupSyle 你在这里添加更多属性它最适合完全控制我在 w10 应用程序中使用它。加上 a 有部分设计时间帮助(仅显示列表):)) 不显示组的标题(GroupView)

于 2015-08-02T20:37:05.863 回答