【问题标题】:How do I access a named Control within my ItemPanelTemplate from the code-behind?如何从代码隐藏访问我的 ItemPanelTemplate 中的命名控件?
【发布时间】:2011-06-29 03:55:54
【问题描述】:

我正在尝试访问 ItemsPanelTemplate 中的 Canvas 对象,以便可以在代码隐藏中直接向其中添加项目。

这是我的 XAML:

 <ListBox x:Name="MyMap" ItemsSource="{Binding MapItems}" 
        Background="Gray"
        SelectionChanged="MyMap_SelectionChanged">

    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas x:Name="MyMapCanvas"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Background="Transparent">
            </Canvas>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

如何在代码隐藏中访问“MyMapCanvas”以向其中添加项目?

我尝试了以下方法:

Canvas canvas = (Canvas)MyMap.ItemsPanel.LoadContent();

ContentPresenter cp = (ContentPresenter)(VisualTreeHelper.GetChild(MyMap, 0));
ItemsPanelTemplate ipt = MyMap.ItemsPanel;
Canvas canvas = ipt.FindName("MyMapCanvas", cp) as Canvas;

提前致谢。

【问题讨论】:

    标签: wpf templates controls code-behind contentpresenter


    【解决方案1】:

    试试这个:

        //your OnLoaded handler
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            Canvas canvas = FindVisualChild<Canvas>(MyMap);
        }
    
        public 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;
        }
    

    【讨论】:

    • 谢谢,它有效。不幸的是,它不会让我向 ItemsPanelTemplate 中的 Canvas 添加东西,这对大多数用途都很有意义。错误:无法显式修改用作 ItemsControl 的 ItemsPanel 的 Panel 的 Children 集合。 ItemsControl 为 Panel 生成子元素。看起来我会修改我的方法。
    • @Paxenos,是的,你应该修改一个方法,你不应该直接将项目添加到画布。
    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多