我正在尝试从Listbox中查找子元素。列表框包含Itemtemplate
。这是我的设计。
我创建了UserControl
。在那里我添加了 ListBox 。
我正在弹出这个控件。这是弹出的代码
GlobalSettings.popup = new Popup();
//GlobalSettings.popup.VerticalOffset = 50;
FilesListControl popupcontrol = new FilesListControl();
popupcontrol.Height = 480;
popupcontrol.Width = 480;
GlobalSettings.popup.Child = popupcontrol;
popupcontrol.fileListbox.ItemsSource = filesList;
LayoutRoot.IsHitTestVisible = false;
GlobalSettings.popup.IsOpen = true;
//Here I need to create checkbox. so thats why I need to find the child elemnt of listbox
popupcontrol.btnDone.Click += (s, args) =>
{
};
此处来自 FilesListControl
的代码<ScrollViewer Grid.Row="0" HorizontalScrollBarVisibility="Auto">
<ListBox Name="fileListbox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox Name="chkFile" CommandParameter="{Binding value}" Content="{Binding Key}" Click="chkFile_Click" FontFamily="Segoe WP SemiLight"></CheckBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
我想找到CheckBox
,即chkFile。这是我的代码
ListBoxItem item = popupcontrol.fileListbox.ItemContainerGenerator.ContainerFromIndex(1) as ListBoxItem;
CheckBox chk = FindFirstElementInVisualTree<CheckBox>(item);
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
{
return (T)child;
}
else
{
var result = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
但没有任何事情发生。我做错了什么?如何访问 CheckBox 点击事件?