如何迭代 LibraryStack 中的元素?

4

我有一个LibraryStack的定义如下:

<s:LibraryStack Name="TaggingContainer" Margin="20" Grid.Row="1" Grid.ColumnSpan="2" AllowDrop="True" Height="300" Width="300" s:SurfaceDragDrop.DragLeave="TaggingContainer_DragLeave" s:SurfaceDragDrop.DragEnter="TaggingContainer_DragEnter" s:SurfaceDragDrop.PreviewDrop="LibraryStack_PreviewDrop">
            <s:LibraryStack.ItemTemplate>
                <DataTemplate>
                    <Label Content="{Binding Name}" Tag="{Binding}" FontSize="20" Margin="10,10,10,10" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" Background="#c49b14" BorderBrush="White" BorderThickness="2" s:Contacts.PreviewContactDown="Label_PreviewContactDown"></Label>
                </DataTemplate>
            </s:LibraryStack.ItemTemplate>
        </s:LibraryStack>

现在在代码后台,我想要遍历包含在LibraryStack中的所有标签(即数据模板中定义的标签)。
但是如果我使用:
foreach (FrameworkElement element in TaggingContainer.Items) {
}

我遍历的是TaggingContainer中的数据对象,而不是Datatemplates。我该如何更改?
1个回答

2
最简单的方法可能是在可视化树中找到每个LibraryStack下的LibraryStackItemLabel。请尝试以下操作:
private void SomeMethod()
{
    // Get All Labels
    List<Label> labels = GetVisualChildCollection<Label>(TaggingContainer);
    foreach (Label label in labels)
    {
        //...
    }
}

或者你可以获取每个元素的容器,然后以此方式获取 Label

foreach (var element in TaggingContainer.Items)
{
    LibraryStackItem libraryStackItem = TaggingContainer.ItemContainerGenerator.ContainerFromItem(element) as LibraryStackItem;
    Label label = VisualTreeHelpers.GetVisualChild<Label>(libraryStackItem);
}

GetVisualChild

private static T GetVisualChild<T>(DependencyObject parent) where T : Visual
{
    T child = default(T);

    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>(v);
        }
        if (child != null)
        {
            break;
        }
    }
    return child;
}

GetVisualChildCollection

public static List<T> GetVisualChildCollection<T>(object parent) where T : Visual
{
    List<T> visualCollection = new List<T>();
    GetVisualChildCollection(parent as DependencyObject, visualCollection);
    return visualCollection;
}
private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Visual
{
    int count = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < count; i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        if (child is T)
        {
            visualCollection.Add(child as T);
        }
        else if (child != null)
        {
            GetVisualChildCollection(child, visualCollection);
        }
    }
}

1
值得注意的是,此方法适用于任何派生自ItemsControl(如listbox、combobox、treeview等)的控件。这里与Surface无关... - Robert Levy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接