My menu is created from bound hierarchical data.
If I have a XamMenuItem instance how do I get the collection of all its child XamMenuItems? In my case if I have a XamMenuItem, called mi for example, if I do a mi.Items[0] and inspect what type is returned, it is the type of my bound hierarchical data not a XamMenuItem as I expected it to be. How do I get the collection of XamMenuItem children?
Thanks,
Pat
Hi Pat,
I have been looking into your post and you can access the children collection of a XamMenuItem using the underlying data. I am attaching a sample application(XamMenuChildren.zip) that demonstrates my approach.
Let me know, if you need any further assistance on this matter.
Sorry, but that isn't what I am looking for. What I am trying to figure out is if I only have the XamMenu, how do I get a list of all XamMenuItems? The XamMenu.Items collection contains a collection of GroupPanelData which is what it is bound to. I need the XamMenuItem for each GroupPanelData element.
So, I have an event handler, I was going to try to get a list of all the XamMenuItems and then iterate the list looking for the one I need (the XamMenuItem.Header would contain the GroupPanelData element). Even better would be to have a GroupPanelData element and be able to get its associated XamMenuItem. I tried to use your Utilities.GetDecendantFromType but it just returns the first XamMenuItem.
You can use the self contained rough prototype, XamMenuFun I've attached and see the below event handler.
private void _scrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e) { int locationIndex = GetLocationIndex(); XamMenu menu = _navigator;
// Get all menu items -- This doesn't work, it always returns the first menu item. XamMenuItem xmi = Utilities.GetDescendantFromType(menu, typeof(XamMenuItem), true) as XamMenuItem; }
Thank you for your response. I came up with similar solution since my post. But yours is more robust, I will implement the way you recommend.
--Pat
Hello Pat,
I have been looking into your requirement and I can suggest you use the following method :
private void GetAllChildrenFromType<T>(DependencyObject parent, List<T> elements) where T : DependencyObject
{
if (elements == null)
elements = new List<T>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
if (VisualTreeHelper.GetChild(parent, i) is T)
elements.Add(VisualTreeHelper.GetChild(parent, i) as T);
}
else
GetAllChildrenFromType<T>(VisualTreeHelper.GetChild(parent, i), elements);
You need to pass the parent(XamMenu) and a list of the children(list of XamMenuItems) which will be populated like e.g. :
List<XamMenuItem> list = new List<XamMenuItem>();
…
private void _scrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
int locationIndex = GetLocationIndex();
XamMenu menu = _navigator;
GetAllChildrenFromType<XamMenuItem>(menu, list);