【问题标题】:Retrieving children of ItemsControl检索 ItemsControl 的子项
【发布时间】:2011-01-24 23:32:32
【问题描述】:

在上面的 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"); 

【问题讨论】:

  • 使用树来处理 ItemsControl 的内容不是一个好习惯。那么你想用 TextBox 做什么呢?
  • 我想为 TextBlock 捕捉鼠标事件。有办法吗?请告诉我。
  • 只需在 ItemsControl 级别挂钩鼠标事件,然后让事件冒泡。
  • 这能回答你的问题吗? How do I access the children of an ItemsControl?

标签: wpf wpf-controls


【解决方案1】:

当您在后面的代码中使用 myPoints 时,您可以使用 ItemContainerGeneratorGetContainerForItem。只需传递您的一件物品即可获得容器。

使用辅助方法获取每个项目的文本块的代码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;
 }

【讨论】:

  • @baalazamon,谢谢,总是忘记“..ItemContainerGenerator.ContainerFromIndex(i)”
猜你喜欢
  • 1970-01-01
  • 2010-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 2023-03-26
相关资源
最近更新 更多