【发布时间】: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