一、界面内容(部分:仅供参考)

<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="" Height="" Margin="0,0,0,0" VerticalAlignment="Center" >
<Image x:Name="img_menuIcon" MouseEnter="MenuItemImage_MouseEnter" MouseLeave="MenuItemImage_MouseLeave" Source="{Binding XPath=@ImagePath0}" ><!--Width="" Height=""--></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="" Height="" Margin="-2,-2,-2,0" Background="#FF939393" BorderBrush="{x:Null}" Foreground="{x:Null}" BorderThickness=""
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=""></Image> <Button.Template>
<ControlTemplate TargetType="Button">
<Grid Background="#939393">
<Image x:Name="ImgOsCanvas" Source="/DrawTool;component/Images/铺展.png" Width="" Height=""></Image>
</Grid>
</ControlTemplate> </Button.Template> </Button>
<!--<TextBlock Height="" Margin="0,0,0,0" Background="#43464f">
</TextBlock>-->
<Menu x:Name="menuTools" ItemsSource="{Binding Source={StaticResource ResourceKey= toolsDS}}" Background="Transparent" ></Menu> </StackPanel> </Window>

二、获取元素的所有子元素

        /// <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 = ; i <= VisualTreeHelper.GetChildrenCount(obj) - ; 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、简便的方式:

List<Image> images = GetChildObjects<Image>(mi);

  2、(比较笨的方法:按照ViasualTree图,一步步找的)

        /// <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 = )
{
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 = ;
DependencyObject dpdcyObj = VisualTreeHelper.GetChild(mi, );
switch (flag)
{
case :
index = ;
break;
case :
index = ;
break;
default:
break;
}
DependencyObject dpdcyObj1 = VisualTreeHelper.GetChild(dpdcyObj, index); //menuItem 1, 子项是2
DependencyObject dpdcyObj2 = VisualTreeHelper.GetChild(dpdcyObj1, );
DependencyObject dpdcyObj3 = VisualTreeHelper.GetChild(dpdcyObj2, );
DependencyObject dpdcyObj4_1 = VisualTreeHelper.GetChild(dpdcyObj3, );
DependencyObject dpdcyObj4_2 = VisualTreeHelper.GetChild(dpdcyObj3, );
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, );
DependencyObject dpdcyObj6 = VisualTreeHelper.GetChild(dpdcyObj5, );
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;
}

WPF:获取控件内的子项的更多相关文章

  1. [WPF]获取控件间的相对位置

    原文:[WPF]获取控件间的相对位置 [WPF]获取控件间的相对位置                             周银辉 我们知道WPF有着比较灵活的布局方式,关于某个控件的坐标,Canv ...

  2. WPF获取控件的句柄

    在WinForm中,获得句柄是一件很容易的事情,This.Handle或者Control.Handle就可以,最近在WPF的开发中发现找不到这个属性,一番查找资料后找到了两种方式. 1,使用Windo ...

  3. WPF 获取控件模板中的控件

    DG是控件名称public T GetVisualChild<T>(DependencyObject parent, Func<T, bool> predicate) wher ...

  4. WPF获取控件内部的ScrollViewer,并控制ScrollViewer操作

    //获取内部  ScrollViewer方法 public static T FindVisualChild<T>(DependencyObject obj) where T : Depe ...

  5. WPF线程中获取控件的值和给控件赋值

    WPF中使用线程操作控件,按平常的操作方法操作的话会报异常:调用线程无法访问此对象,因为另一个线程拥有该对象.所以我们要使用Dispatcher类的BeginInvoke()与Invoke()方法.B ...

  6. WPF默认控件模板的获取和资源词典的使用

    一.获取默认的控件模板 WPF修改控件模板是修改外观最方便的方式,但是会出现不知道原来的控件的模板长什么样,或者想用来参考的,下面分享一下获取某控件默认控件模板的方式(已Button为例): 1.创建 ...

  7. WPF常用控件应用demo

    WPF常用控件应用demo 一.Demo 1.Demo截图如下: 2.demo实现过程 总体布局:因放大缩小窗体,控件很根据空间是否足够改变布局,故用WrapPanel布局. <ScrollVi ...

  8. asp.net js获取控件ID

    ClientID是由ASP.Net生成的服务器控件得客户端标识符,当这个控件生成到客户端页面的时候,在客户端代码访问该控件时就需要通过ClientID来访问. 以文本框为例: 一.未使用母版页 js可 ...

  9. WPF Image控件中的ImageSource与Bitmap的互相转换

    原文:WPF Image控件中的ImageSource与Bitmap的互相转换  1.从bitmap转换成ImageSource [DllImport("gdi32.dll", ...

随机推荐

  1. linux input输入子系统应用分析

    输入设备(如按键.键盘.触摸屏.鼠标等)是典型的字符设备,其一般的工作机理是底层在按键.触摸等动作发送时产生一个中断(或驱动通过timer定时查询),然后CPU通过SPI.I2 C或外部存储器总线读取 ...

  2. python 环境问题

    1. 查看python安装的模块及版本 $pip freeze Babel== Flask== Flask-HTTPAuth== Flask-RESTful== Flask-SQLAlchemy==2 ...

  3. 堡垒机 paramiko 自动登陆代码

    #!/usr/bin/env python # Copyright (C) - Robey Pointer <robeypointer@gmail.com> # # This file i ...

  4. Vue.2.0.5-生产环境部署

    删除警告 为了减少文件大小,Vue 精简独立版本已经删除了所有警告,但是当你使用 Webpack 或 Browserify 等工具时,你需要一些额外的配置实现这点. Webpack 使用 Webpac ...

  5. Perl Debug error: SetConsoleMode failed, LastError=|6|

    Windows Strawberry Perl. 解决办法: 1. 设置环境变量 TERM = dumb 2. 重启 CMD 参考资料: http://padre.perlide.org/trac/t ...

  6. 记32位程序(使用3gb用户虚拟内存)使用D3DX9导致的一个崩溃的问题

    为了增加32位程序的用户虚拟内存的使用量,我们使用了/LARGEADDRESSAWARE编译选项来使32位程序可能使用到3gb的内存,能否使用到3gb内存也跟平台.系统和设置有关系,现摘抄部分作为参考 ...

  7. PAT 解题报告 1048. Find Coins (25)

    1048. Find Coins (25) Eva loves to collect coins from all over the universe, including some other pl ...

  8. 一个想了好几天的问题——关于8086cpu自己编写9号中断不能单步的问题

           在<汇编语言>第十五章中我们可能遇到这样的问题:程序运行正确,但是debug单步调试,却无法运行,修改int 9h中断例程入口地址的指令,虚拟模式下,debug提示指令无效, ...

  9. 最大权闭合图(Road constructions)hdu3917

    题意:给出n个城市,k条道路,每条道路都有其负责的公司和花费,m个公司来投标修路,给出m个公司承包需要交纳的赋税,如果第i个公司负责修1-->2路,第j个公司负责修2-->3路,如果选择了 ...

  10. yii遍历行下的每列数据(小1月考)

    效果图: 控制器(1种): //显示列表    public function actionList()    {        //实例化对象        $model= new Qiu();   ...