所以如果我有一个项目控件并且想要在后面的代码中获取画布,我该怎么办?我可以获取itemscontrol,但是我该怎么做才能检索画布?我试过了
Canvas c1 = ic.FindName("MarkerCanvas") as Canvas;
其中ic是itemscontrol。我也尝试过itemscontrol的各种模板下的findname函数,但效果不大。我该怎么办?
<ItemsControl
>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas
x:Name="MarkerCanvas"
SnapsToDevicePixels="false"
/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl
>
答案 0 :(得分:2)
我找到了这个并测试它的工作原理:
How can I find WPF controls by name or type?
只需将通话更改为
即可Canvas foundCanvas =UIHelper.FindChild<Canvas>(Application.Current.MainWindow, "MarkerCanvas");
答案 1 :(得分:1)
如果你有Canvas
的孩子,说myControl
,那么这应该有用:
var dObj = myControl as DependencyObject;
while (!(dObj is Canvas && (dObj as Canvas).Name == "MarkerCanvas")) dObj == VisualTreeHelper.GetParent(dObj);