wpf - 检索 ItemsControl 的子项

标签 wpf wpf-controls

在上面的 XAML 代码中,我使用下面的代码获取子项(ItemsCotnrol x:Name="PointsList)并获取计数 = 0。你能帮我解决这个问题吗。

        int count = VisualTreeHelper.GetChildrenCount(pointsList);
        if (count > 0)
        {
            for (int i = 0; i < count; i++)
            {
                UIElement child = VisualTreeHelper.GetChild(pointsList, i) as UIElement;
                if (child.GetType() == typeof(TextBlock))
                {
                    textPoints = child as TextBlock;
                    break;
                }
            }
        }

pointsList 定义如下。
pointsList = (ItemsControl)GetTemplateChild("PointsList"); 

最佳答案

当您在后面的代码中使用 myPoints 时,您可以使用 ItemContainerGenerator获取ContainerForItem。只需传递您的一件元素即可获得容器。

使用辅助方法 GetChild 获取每个项目的文本块的代码:

for (int i = 0; i < PointsList.Items.Count; i++)
{
     // Note this part is only working for controls where all items are loaded  
     // and generated. You can check that with ItemContainerGenerator.Status
     // If you are planning to use VirtualizingStackPanel make sure this 
     // part of code will be only executed on generated items.
     var container = PointsList.ItemContainerGenerator.ContainerFromIndex(i);
     TextBlock t = GetChild<TextBlock>(container);
}

从 DependencyObject 获取子对象的方法:
public T GetChild<T>(DependencyObject obj) where T : DependencyObject
{
    DependencyObject child = null;
    for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
         child = VisualTreeHelper.GetChild(obj, i);
         if (child != null && child.GetType() == typeof(T))
         {
             break;
         }
         else if (child != null)
         {
             child = GetChild<T>(child);
             if (child != null && child.GetType() == typeof(T))
             {
                 break;
             }
         }
     }
     return child as T;
 }

关于wpf - 检索 ItemsControl 的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4788422/

相关文章:

c# - WPF 中的倒角半径(类似于负半径)

c# - 将文本框拆分为 4 个独立的文本框,但保存在一个 EF 字段中

c# - 无法将单击事件传递/绑定(bind)到 WPF 用户控件

c# - 如何制作 UI-MarkupExtension

wpf - 无法通过类型(!)(wpf)找到模板化控件的父级

c# - Style.TargetType、对话框和子类化 WPF 控件

c# - 文本 block 在数据网格 WPF 中选择前景色

c# - 我的部分 GUI 速度很慢

c# - 我们可以知道窗口是否已被用户或 WPF 上的代码关闭吗?

c# - 如何创建一个 UI 来模拟 WPF 中的 RAM 分区?