4

So If I have an items control and want to get the canvas in the code behind, what should I do? I can get the itemscontrol, but then what do I do to retrieve the canvas? I have tried

Canvas c1 = ic.FindName("MarkerCanvas") as Canvas;

where ic is the itemscontrol. I have also tried the findname function under the itemscontrol's various templates to little avail. What should I be doing?

     <ItemsControl 
          >
          <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
              <Canvas 
                x:Name="MarkerCanvas"
                SnapsToDevicePixels="false"
                />
            </ItemsPanelTemplate>
          </ItemsControl.ItemsPanel>
     </ItemsControl 
          >
James Joshua Street
  • 3,259
  • 10
  • 42
  • 80

2 Answers2

2

I found this and test it it work :

How can I find WPF controls by name or type?

just change the call to

Canvas foundCanvas =UIHelper.FindChild<Canvas>(Application.Current.MainWindow, "MarkerCanvas");
Community
  • 1
  • 1
Akrem
  • 5,033
  • 8
  • 37
  • 64
  • wasn't planning on using this originally cause i figured that the findname function on the template itself should work, but it doesn't appear to work if the template hasn't been applied yet, so it's easier to just use this function. – James Joshua Street Feb 24 '14 at 16:36
1

If you have something which is the child of that Canvas, say myControl, then this should work:

var dObj = myControl as DependencyObject;
while (!(dObj is Canvas && (dObj as Canvas).Name == "MarkerCanvas")) dObj == VisualTreeHelper.GetParent(dObj);
dkozl
  • 32,814
  • 8
  • 87
  • 89