我正在尝试访问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;
提前致谢。
答案 0 :(得分:2)
试试这个:
//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;
}