UWP ListView:如何在选择项目时展开项目?

时间:2016-10-13 16:40:29

标签: uwp uwp-xaml

我有一个包含某个项目的列表视图。我想在选择一个项目时展开项目以显示详细信息,我该怎么办?

1 个答案:

答案 0 :(得分:3)

我没有仔细检查CustomControl由@AVK Naidu提供的,这很好,似乎可以解决你的问题。但是我需要在这里说,完全可以使用默认的ListView控件执行此操作,只需在选中时DataTemplate更改ListViewItem即可。< / p>

仅举例来说:

<Page.Resources>
    <DataTemplate x:Name="Normal" x:Key="Normal">
        <TextBlock Text="{Binding Name}" />
    </DataTemplate>
    <DataTemplate x:Name="Detail" x:Key="Detail">
        <StackPanel>
            <TextBlock Text="{Binding Name}" FontSize="30" Foreground="Red" HorizontalAlignment="Center" />
            <TextBlock Text="Details:" FontSize="30" Foreground="Blue" Margin="0,10" />
            <TextBlock Text="{Binding Details}" FontSize="20" />
        </StackPanel>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView ItemTemplate="{StaticResource Normal}"
              ItemsSource="{x:Bind Collection}" SelectionChanged="listView_SelectionChanged" />
</Grid>

listView_SelectionChanged后面的代码:

private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Assign DataTemplate for selected items
    foreach (var item in e.AddedItems)
    {
        ListViewItem lvi = (sender as ListView).ContainerFromItem(item) as ListViewItem;
        lvi.ContentTemplate = (DataTemplate)this.Resources["Detail"];
    }
    //Remove DataTemplate for unselected items
    foreach (var item in e.RemovedItems)
    {
        ListViewItem lvi = (sender as ListView).ContainerFromItem(item) as ListViewItem;
        lvi.ContentTemplate = (DataTemplate)this.Resources["Normal"];
    }
}

结果:

enter image description here