c# - 尝试使用 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 添加了内容,如果我删除了导致崩溃的代码,它会正确显示。
编辑:我进行了更多实验,似乎在我尝试访问它时没有呈现视图。但是,如果我稍后再添加它,如果有人在时间完成之前单击复选框,它可能会出错。有没有办法在计算视图之后立即执行此操作,但在与它进行交互之前?
解决方案
您需要将 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;
}
推荐阅读
- swift - swift AVAudioEngine 和 AVAudioSinkNode sampleRate 转换
- html - 我应该如何处理 validateDOMNesting(...) 错误?
- java - 从 Java 向 Oracle 插入数千条记录,如何获得最佳性能?
- python - 如何用 Python 替换部分列 String SQLite3
- javascript - 动态更改时如何更改MenuItem(antd)的样式?
- javascript - 对于 Material UI,我如何知道每个组件的属性是什么?
- macos - 如何生成 F# 签名文件(没有 Visual Studio)
- c++ - wxWidgets 安装时标头路径不正确
- r - 累积复合股票收益
- r - R 中的 GenomicFeatures 函数“transcriptsByOverlaps()”出错