c# - 在ListView的DataTemplate中设置Data Type时如何访问ListView Items?

标签 c# xaml listview uwp

我正在开发一个 UWP 应用程序。我想遍历页面中 ListView 的所有 ListViewItems。这是 ListView 的 xaml。

<ListView x:Name="DownloadTaskListView"
                  ItemsSource="{x:Bind ViewModel.CompletedDownloads}"
                  HorizontalContentAlignment="Stretch" 
                  Background="{x:Null}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:DownloadTask">
                    <Grid x:Name="ItemViewGrid" Background="{x:Null}" Margin="4,0,0,0">
                    ....
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="HorizontalAlignment" Value="Stretch" />
                    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                    <Setter Property="BorderThickness" Value="0" />
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>

我使用这段代码来实现这一点。

foreach(ListViewItem item in DownloadTaskListView.Items)
{
     // Do something useful

}

但它给了我一个异常(exception)。因为我设置了 DataTemplate 的数据类型,所以运行时抛出一个异常,它无法从 DownloadTask(在本例中为数据类型)转换为 ListViewItem。所以我想问一下访问ListViewItems的另一种方式是什么?

最佳答案

您可以使用 ItemsControl.ContainerFromItem method找到与指定项目对应的容器,然后获取该容器的根元素,在您的例子中它是一个 Grid。例如像这样:

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    foreach (var item in DownloadTaskListView.Items)
    {
        var listviewitem = item as DownloadTask;
        var container = DownloadTaskListView.ContainerFromItem(listviewitem) as ListViewItem;
        var ItemViewGrid = container.ContentTemplateRoot as Grid;
        //TODO:
    }
}

请注意,如果您想在 ListView 的 SelectionChanged 事件中使用此方法,只需将所选项目传递给 ContainerFromItem 方法即可,否则它不会找到 ListBoxItem

我应该说,如果可能的话,使用数据绑定(bind)会更好。

关于c# - 在ListView的DataTemplate中设置Data Type时如何访问ListView Items?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38514321/

相关文章:

Android 在 listView 中设置图像

c# - Facebook 图形 API : delete notification

c# - 解析 C Sharp 中的嵌套文本

c# - 在 WebBrowser 控件中禁用警告窗口

c# - Windows Phone 8.1 应用多语言

c# - ListView 列标题液体大小?

c# - OpenGL 不在我的 C# 面板上显示/绘制

c# - 仅 WPF TabItem 标题样式

c# - Xamarin.Forms 的 native 嵌入 : not finding UIKit in global namespace,

c# - WPF Listview 数据绑定(bind)到通用列表,由 WCF 服务动态填充