2

我正在尝试从 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>

我想找到CheckBoxie 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 Click 事件?

4

0 回答 0