WPF:获取控件内的子项
一、界面内容(部分:仅供参考)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<Window> <Window.Resources> <!--工具数据源--> <XmlDataProvider x:Key="toolsDS" Source="Config\Tools\Tools.xml" XPath="Tools/Tool"></XmlDataProvider> <!--Tool模板--> <HierarchicalDataTemplate DataType="Tool" ItemsSource="{Binding XPath=Tool}" > <StackPanel Orientation="Vertical" VerticalAlignment="Center" Margin="0,10,0,0" > <!--MouseEnter="MenuItemImage_MouseEnter" MouseLeave="MenuItemImage_MouseLeave"--> <TextBlock Tag ="{Binding XPath=@Name}" Width="38" Height="38" Margin="0,0,0,0" VerticalAlignment="Center" > <Image x:Name="img_menuIcon" MouseEnter="MenuItemImage_MouseEnter" MouseLeave="MenuItemImage_MouseLeave" Source="{Binding XPath=@ImagePath0}" ><!--Width="38" Height="38"--></Image> </TextBlock> <TextBlock x:Name="img_Title" Text ="{Binding XPath=@Title}" VerticalAlignment="Center" HorizontalAlignment="Center" TextAlignment="Center" Margin="0,3,0,0" Foreground="#FFD1D1D1" FontSize="{Binding XPath=@FontSize}" MouseEnter="MenuItemText_MouseEnter" MouseLeave="MenuItemText_MouseLeave" > </TextBlock> </StackPanel> </HierarchicalDataTemplate> </Window.Resources> <StackPanel x:Name="StackBlist" Orientation="Vertical" MenuItem.Click="MenuItem_Click" VerticalAlignment="Top" Background="#43464f"> <Button x:Name="btnOS" Click="btnOS_Click" Width="88" Height="26" Margin="-2,-2,-2,0" Background="#FF939393" BorderBrush="{x:Null}" Foreground="{x:Null}" BorderThickness="0" PreviewMouseLeftButtonDown="StackBlist_PreviewMouseLeftButtonDown" PreviewMouseLeftButtonUp="StackBlist_PreviewMouseLeftButtonUp" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{x:Null}" IsEnabled="True" IsHitTestVisible="True" IsManipulationEnabled="False"> <!--PreviewMouseMove="StackBlist_PreviewMouseMove"--> <Image x:Name="ImgOsCanvas" Source="/DrawTool;component/Images/铺展.png" Height="20"></Image> <Button.Template> <ControlTemplate TargetType="Button"> <Grid Background="#939393"> <Image x:Name="ImgOsCanvas" Source="/DrawTool;component/Images/铺展.png" Width="88" Height="20"></Image> </Grid> </ControlTemplate> </Button.Template> </Button> <!--<TextBlock Height="10" Margin="0,0,0,0" Background="#43464f"> </TextBlock>--> <Menu x:Name="menuTools" ItemsSource="{Binding Source={StaticResource ResourceKey= toolsDS}}" Background="Transparent" ></Menu> </StackPanel> </Window>
二、获取元素的所有子元素
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 获得指定元素的所有子元素 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public List<T> GetChildObjects<T>(DependencyObject obj) where T : FrameworkElement { DependencyObject child = null; List<T> childList = new List<T>(); for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++) { child = VisualTreeHelper.GetChild(obj, i); if (child is T) { childList.Add((T)child); } childList.AddRange(GetChildObjects<T>(child)); } return childList; }
如:获取Menu的所有MenuItem项
List<System.Windows.Controls.MenuItem> mis = GetChildObjects<System.Windows.Controls.MenuItem>(this.menuTools);
三、更改菜单项内容
1、简便的方式:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
List<Image> images = GetChildObjects<Image>(mi);
2、(比较笨的方法:按照ViasualTree图,一步步找的)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 设置菜单项的图标、标题 /// </summary> /// <param name="mi">菜单项</param> /// <param name="isConnected">是否已连接</param> /// <param name="title"></param> /// <param name="flag"></param> /// <returns></returns> private bool SetMenuContent(System.Windows.Controls.MenuItem mi,bool isConnected,string title = null,int flag = 0) { bool isSuccess = true; try { XmlElement xe = mi.Header as XmlElement; _selectedXelmt = xe; string front = @"pack://application:,,,"; string menuItemTitle = xe.Attributes["Title"].Value; string imgPath = front + xe.Attributes["ImagePath"].Value; string imgPath0 = front + xe.Attributes["ImagePath0"].Value; int index = 3; DependencyObject dpdcyObj = VisualTreeHelper.GetChild(mi, 0); switch (flag) { case 0: index = 3; break; case 1: index = 2; break; default: break; } DependencyObject dpdcyObj1 = VisualTreeHelper.GetChild(dpdcyObj, index); //menuItem 1, 子项是2 DependencyObject dpdcyObj2 = VisualTreeHelper.GetChild(dpdcyObj1, 0); DependencyObject dpdcyObj3 = VisualTreeHelper.GetChild(dpdcyObj2, 0); DependencyObject dpdcyObj4_1 = VisualTreeHelper.GetChild(dpdcyObj3, 0); DependencyObject dpdcyObj4_2 = VisualTreeHelper.GetChild(dpdcyObj3, 1); TextBlock tb = dpdcyObj4_2 as TextBlock; if (isConnected && !string.IsNullOrEmpty(title)) { tb.Text = title; } else { tb.Text = menuItemTitle; } //System.Windows.Forms.MessageBox.Show(tb.Text); DependencyObject dpdcyObj5 = VisualTreeHelper.GetChild(dpdcyObj4_1, 0); DependencyObject dpdcyObj6 = VisualTreeHelper.GetChild(dpdcyObj5, 0); Image img = dpdcyObj6 as Image; if (isConnected) { //string srcPath = img.Source.ToString().Replace("0", string.Empty); //img.Source = new BitmapImage(new System.Uri(srcPath)); img.Source = new BitmapImage(new System.Uri(imgPath)); } else { img.Source = new BitmapImage(new System.Uri(imgPath0)); } //System.Windows.Forms.MessageBox.Show(img.ToString()); isSuccess = true; } catch (Exception ex) { isSuccess = false; } return isSuccess; }