首页 > 解决方案 > 尝试使用 ContainerFromIndex() 获取 ListView 的子级返回 null

问题描述

我正在尝试检查我的 ListView 中的复选框:

Grid specialGrid = (Grid) listView1.ContainerFromIndex(index);
CheckBox specialBox = (CheckBox) specialGrid.FindName("Special");
specialBox.IsChecked = true;

<ListView x:Name="listView1">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="x:String">
            <Grid x:Name="LineW">
                <CheckBox x:Name="Special" Grid.Column="1" Checked="Special_Checked" Unchecked="Special_Unchecked"/>

这本质上是我的 ListView。但是调用 ContainerFromIndex() 会返回 null,即使该项目存在(当然,只要我消除了崩溃的原因)我不明白出了什么问题。我试过打电话

int number = listView1.Items.Count;

在此之前,由于某种原因它返回 0。但我确实向 ObservableCollection 添加了内容,如果我删除了导致崩溃的代码,它会正确显示。

编辑:我进行了更多实验,似乎在我尝试访问它时没有呈现视图。但是,如果我稍后再添加它,如果有人在时间完成之前单击复选框,它可能会出错。有没有办法在计算视图之后立即执行此操作,但在与它进行交互之前?

标签: c#uwp

解决方案


您需要将 ObservableCollection 提供给列表视图的 ItemSource 属性。x:Name with in Template 无法访问。看看下面的例子

    /*Xaml Code*/
     <Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <ListView ItemsSource="{x:Bind items,Mode=OneWay}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="local:Item">
                    <StackPanel Orientation="Horizontal">
                        <CheckBox IsChecked="{x:Bind is_checked}"></CheckBox>
                        <TextBlock Text="{x:Bind text}"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>    
//C# code
namespace App1
{
    public sealed partial class MainPage : Page
    {
        ObservableCollection<Item> items;
        public MainPage()
        {
            items = new ObservableCollection<Item>();
            items.Add(new Item() { is_checked = true, text = "item1" });
            items.Add(new Item() { is_checked = true, text = "item2" });
            items.Add(new Item() { is_checked = false, text = "item3" });
            this.InitializeComponent();
        }


    }
    public class Item
    {
      public   bool is_checked { get; set; }
      public  string text { get; set; }
    }
}

编辑 要获取具有特定文本的项目,请使用 LINQ。检查下面的示例代码

public Int32 getindexofitem()
{
  var index = items.IndexOf(items.Single(g => g.text == "item2"));
  return index;
} 

推荐阅读