本文介绍了wpf 强制构建可视化树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 ItemsControl 和 Grid 作为 ItemsPanelTemplate

I have ItemsControl with Grid as ItemsPanelTemplate

<ItemsControl ItemsSource="{Binding CellCollection}" Name="CellGrid">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid Name="grid" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

我在代码隐藏中使用此 ItemControl 创建了一些 UserControl,然后我需要创建 RowDefinitions 和 ColumnDefinitons.我用这种方法得到网格":

I create some UserControl with this ItemControl inside in code-behind, and then i need to create RowDefinitions and ColumnDefinitons. I use this method to get "grid":

private TChildItem FindVisualChild<TChildItem>(DependencyObject obj) where TChildItem : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            var child = VisualTreeHelper.GetChild(obj, i);

            if (child != null && child is TChildItem)
                return (TChildItem)child;

            var childOfChild = FindVisualChild<TChildItem>(child);

            if (childOfChild != null)
                return childOfChild;
        }

        return null;
    }

但是如果我在显示 UserControl 之前调用此方法,它会返回 null,所以我无法找到访问网格",并且当 UserControl 出现时,它的显示与我预期的不同.

But if i call this method before showing UserControl it returns null, so I cant find access "grid" and when UserControl appears it displayed not as I expected.

我试图用谷歌搜索,但我发现的只是假设 VisualTree 不会为 ItemControl 构建,直到它显示在表单上.

I tried to google but all i found is assumption that VisualTree not building for ItemControl until it showed on form.

有什么建议吗?感谢和抱歉英语不好;)

Any suggestions?Thanks and sorry for bad english ;)

推荐答案

您可以调用 ApplyTemplate 这告诉元素应用模板并构建可视化树.

You can make a call to ApplyTemplate this tells the element to apply the template and build the visual tree.

尽管如此,这并不会一直应用模板.在这种情况下,您必须首先调用 ItemsControl 上的 ApplyTemplate(),然后调用 var item_presenter = FindVisualChild(items_control),然后您必须调用 item_presenter.ApplyTemplate() 现在您将强制 Grid 进入 VisualTree.

Although, this doesn't apply templates all the way down.In this case you would first have to call ApplyTemplate() on the ItemsControl, then var item_presenter = FindVisualChild<ItemsPresenter>(items_control), then you have to call item_presenter.ApplyTemplate() and now you will have forced the Grid into the VisualTree.

这篇关于wpf 强制构建可视化树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 18:44