我在 WPF 应用程序中有一个 ListView,里面有 CheckBox。
我正在使用 ChapterID 和 ChapterTitles 通过 DataTable 填充 ListView
<ListView x:Name="listViewChapter" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderThickness="0" SelectionMode="Multiple" Margin="0,2,-1,3" TabIndex="17" Grid.ColumnSpan="2">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" />
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</ListView.GroupStyle>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" HorizontalAlignment="Left" VerticalAlignment="Center">
<CheckBox Name="chkChapterTitle" VerticalAlignment="Center" Margin="0,0,0,0" Tag="{Binding ChapterID}" Content="{Binding ChapterTittle}" Checked="chkChapterTitle_Checked" Unchecked="chkChapterTitle_Unchecked" IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListViewItem},Path=IsSelected}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
现在我想访问 CheckBoxes 里面检查...
我的代码是...
private void ToCheckChapters()
{
for (int i = 0; i < listViewChapter.Items.Count; i++)
{
// Get a all list items from listbox
ListViewItem ListBoxItemObj = (ListViewItem)listViewChapter.ItemContainerGenerator.ContainerFromItem(listViewChapter.Items[i]);
//bool check = ListBoxItemObj.HasContent;
// find a ContentPresenter of that list item.. [Call FindVisualChild Method]
ContentPresenter ContentPresenterObj = FindVisualChild<ContentPresenter>(ListBoxItemObj);
// call FindName on the DataTemplate of that ContentPresenter
DataTemplate DataTemplateObj = ContentPresenterObj.ContentTemplate;
CheckBox Chk = (CheckBox)DataTemplateObj.FindName("chkChapterTitle", ContentPresenterObj);
Chk.IsChecked = true;
}
}
private childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
但在这段代码中 ContentPresenterObj 始终为空......