WPF:设置MenuItem多种不同状态图标

摘要:
B、 发布评论。跟踪并单击弹出的子菜单项时,image.source的值永远不是所选的新图标。

需求描述:

  给MenuItem内部的子Image设置默认图标(鼠标leave)、鼠标hover图标、和选中时的图标。

  注:是给Menu内个别MenuItem修改,并且是弹出子菜单。

问题描述:

  1)前提:Image绑定数据源成功,且Image设置默认图标(鼠标leave)、鼠标hover图标,已经在Image的对应事件中,通过image.source设置成功;

      2)思路:在点击弹出的子菜单项时,通过修改image绑定的数据源,来设置新选中图标。

      3)问题:修改image绑定的数据源成功,但图标依然显示的是默认图标。

      4)分析:

                a、注销掉在Image设置默认图标(鼠标leave)、鼠标hover图标的代码,则点击弹出的子菜单项时,设置新选中图标成功。

                b、释放注释,跟踪点击弹出的子菜单项时,image.source的值一直不是选中的新图标。

                c、释放注释,仅注释掉给image.source的相关代码,点击弹出的子菜单项时,设置新选中图标成功。跟踪image.source的值是选中的新图标。

      5)结论:虽然修改image绑定的数据源成功,若存在给image.source 赋值操作,数据源并未起作用。

解决方法:

  1、点击弹出的子菜单项时,将image绑定的数据源设置为选中的图标;

  2、Image设置默认图标(鼠标leave)、鼠标hover图标时,不修改选中时显示的图标,仅在取消选中操作时,修改显示的图标;

      3、点击弹出的子菜单项时,不仅将image绑定的数据源设置为选中的图标,而且获取该Menuitem的Image,将image.source的值是选中的新图标。

     注:

           操作的主体是数据源,其次才是控件,正常情况下控件的显示是随数据源变化。

          

参考代码如下:

1、设置Menuitem内Image的图片

WPF:设置MenuItem多种不同状态图标第1张WPF:设置MenuItem多种不同状态图标第2张
        /// <summary>
        /// 设置菜单项内的图片(因为Image.source赋值后,显示不出绑定的图片,所以又重新赋值)
        /// </summary>
        /// <param name="mi"></param>
        /// <param name="isFlag"></param>
        /// <returns></returns>
        private bool SetMenuitemImage(System.Windows.Controls.MenuItem mi,bool isFlag)
        { 
            bool isSuccess= false;
            try
            {
                if (mi != null)
                {
                    XmlElement xe = mi.Header as XmlElement;
                        string imgPath0 = xe.Attributes["ImagePath0"].Value;//front + 
                        List<Image> images = this.GetChildObjects<Image>(mi);
                    if (!isFlag)
                    {
                        xe.Attributes["ImagePath"].Value = imgPath0.Replace("2", string.Empty);
                        xe.Attributes["ImagePath0"].Value = imgPath0.Replace("2", "0");
                        images[0].Source = new BitmapImage(new System.Uri(@"pack://application:,,," + xe.Attributes["ImagePath0"].Value));
                    }
                    else
                    {
                        xe.Attributes["ImagePath"].Value = imgPath0.Replace("0", "2");
                        xe.Attributes["ImagePath0"].Value = imgPath0.Replace("0", "2");
                        images[0].Source = new BitmapImage(new System.Uri(@"pack://application:,,," + xe.Attributes["ImagePath0"].Value));
                    }
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
            }

            return isSuccess;
        }
View Code

2、Image设置默认图标(鼠标leave)、鼠标hover图标时,不修改选中时显示的图标

WPF:设置MenuItem多种不同状态图标第1张WPF:设置MenuItem多种不同状态图标第4张
        private void MenuItemImage_MouseEnter(object sender, EventArgs e)
        {
            Image img = sender as Image;
            if (img == null && sender is StackPanel)//System.Windows.Controls.MenuItem)//StackPanel//
            {
                //System.Windows.Controls.MenuItem mi = sender as System.Windows.Controls.MenuItem;
                //StackPanel sp = mi.DataContext as StackPanel;

                StackPanel sp = sender as StackPanel;
                img = sp.Children[0] as Image;
                Thread.Sleep(10);
            }
            _logger.Info(sender.GetType().ToString());
            if (img != null && string.IsNullOrEmpty(_srcImgPath))
            {
                //_srcImgPath = img.Source.ToString();
                //_logger.Info(_srcImgPath);
                string srcPath = img.Source.ToString();
                string newPath = srcPath.Replace("0", string.Empty);

                if (!srcPath.Contains("2"))
                {
                    img.Source = new BitmapImage(new System.Uri(newPath));
                }
                
            }


            _imgFlag = true;
            //img.Source = new BitmapImage(new System.Uri("pack://application:,,," + _selectedXelmt.Attributes["ImagePath"].Value));// "{Binding XPath=@ImagePath0}";
            //BaseUri    pack://application:,,,/DrawTool;component/startwindow.xaml    Unknown        System.Windows.Media.Imaging.BitmapFrameDecode
            
        }

        private void MenuItemImage_MouseLeave(object sender, EventArgs e)
        {
            Image img = sender as Image;
            if (img == null && sender is StackPanel)//System.Windows.Controls.MenuItem)
            {
                //System.Windows.Controls.MenuItem mi = sender as System.Windows.Controls.MenuItem;
                //StackPanel sp = mi.DataContext as StackPanel;
                StackPanel sp = sender as StackPanel;

                img = sp.Children[0] as Image;
                Thread.Sleep(10);
            }
            if (img != null )//&& !string.IsNullOrEmpty(_srcImgPath)
            {
                string srcPath = img.Source.ToString();
                if (!srcPath.Contains("0") && !srcPath.Contains("1") && !srcPath.Contains("2"))
                {
                    int dotIndex = srcPath.LastIndexOf('.');
                    string imgExt = srcPath.Substring(dotIndex);
                    string newPath = srcPath.Substring(0, srcPath.Length - imgExt.Length) + "0" + imgExt;
                
                    img.Source = new BitmapImage(new System.Uri(newPath));
                }

                //img.Source = new BitmapImage(new System.Uri(_srcImgPath));
                _srcImgPath = string.Empty;
                //_logger.Info(_srcImgPath);
            }
            //Thread.Sleep(10);
            _imgFlag = false;
            _logger.Info(sender.GetType().ToString());
            //img.Source = new BitmapImage(new System.Uri("pack://application:,,," + _selectedXelmt.Attributes["ImagePath"].Value));// "{Binding XPath=@ImagePath0}";
            //BaseUri    pack://application:,,,/DrawTool;component/startwindow.xaml    Unknown        System.Windows.Media.Imaging.BitmapFrameDecode
        }
View Code

免责声明:文章转载自《WPF:设置MenuItem多种不同状态图标》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Flutter 总结apk打包上架问题(keystore,依赖包下载报错,apk文件项目请求报错等)iOS-reveal 的使用下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

wpf学习笔记更新数据源

此示例基于wpf学习笔记-指定数据源1.让对象实现INotifyPropertyChanged接口,以便属性更改发出通知 {publicPerson(){}publicPerson(stringname,intage){this.name=name;this.age=age;}stringname;publicstringName{get{returnth...

【WPF】查找父/子控件(元素、节点)

整理一下项目中常用的找控件功能,包括找父/子控件、找到所有同类型子控件(比如ListBox找到所有Item)。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; us...

WPF 进度条

前台新建一个控件ProgressBar控件,并命名为pbDown            WebRequest request = WebRequest.Create("http://files.cnblogs.com/fornet/404.rar");            WebResponse respone = request.GetResponse...

WPF 制作圆角按钮

在程序对应坐置插入以下代码,或是先拖一个按钮控件到窗体中,再替换对应的代码。 修改CornerRadius="18,3,18,3" 就可以改变圆角大小 按钮效果: <Button Content="Button" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top...

WPF 自定义按钮 Style

<Style TargetType="{x:Type Button}" x:Key="DefaultButton"> <Setter Property="Foreground" Value="White"/> <Setter Property="...

WPF笔记一

笔记内容: BUG、WPF运行窗体时调用Hide()方法,然后再Show()异常的解决方案 WPF 窗体设置为无边框 选择本地文件 选择文件夹 WPF实现右下角弹出消息窗口 WPF 显示 HTTP 网络图片 获得当前应用软件的版本 获取匿名对象(object)的属性值 WPF *.exe给另一个*.exe传值 C# zip压缩与zip解压,下载地址:点击...