欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MVVM模式下WPF动态绑定展示图片

程序员文章站 2022-06-09 08:54:47
mvvm模式下wpf动态展示图片,界面选择图标,复制到项目中固定目录下面,保存到数据库的是相对路径,再次读取的时候是根据数据库的相对路径去获取项目中绝对路径的图片展示。...

mvvm模式下wpf动态展示图片,界面选择图标,复制到项目中固定目录下面,保存到数据库的是相对路径,再次读取的时候是根据数据库的相对路径去获取项目中绝对路径的图片展示。

首先在viewmodel中

//属性定义
    bitmapimage _imagesource;
    /// <summary>
    /// 显示的图标
    /// </summary>
    public bitmapimage imagesource
    {
      get { return _imagesource; }
      set
      {
        _imagesource = value;
        notifyofpropertychange("imagesource");
      }
    }

    string _imagepath;
    /// <summary>
    /// 显示的图标路径
    /// </summary>
    public string imagepath
    {
      get { return _imagepath; }
      set
      {
        _imagepath = value;
        notifyofpropertychange("imagepath");
      }
    }

//初始化数据
//编辑的时候绑定数据
public groupinfoviewmodel(sys_right_group groupinfo, opertype type)
    {
      if (type == opertype.edit || type == opertype.show)
      {
        isadd = false;
        titlename = "编辑分组";
        rightgroup = groupinfo;
        imagepath = groupinfo.imagepath; 
        getimgdata(groupinfo.imagepath);
      }
    }
    /// <summary>
    /// 获取图片数据
    /// </summary>
    /// <param name="imgpath">相对路径</param>
    private void getimgdata(string imgpath)
    {
      if (string.isnullorempty(imgpath)) return;
      try
      {
        
        string filename = system.environment.currentdirectory + imgpath; //获取文件的绝对路径
        byte[] buf;
        if (!pathtobyte(filename, out buf))
        {
          messagehelper.showautoclosewarning("获取图标失败");
          return;
        }
        imagesource =bytetoimage(buf);
      }
      catch (exception ex)
      {
        throw ex;
      }
    }

//界面选择图片按钮事件
   /// <summary>
    /// 修改图片
    /// </summary>
    public void changedicon()
    {
      try
      {
        openfiledialog open = new openfiledialog();
        open.filter = string.format("照片|*.jpg;*.jpeg;*.png;*.gif;*.bmp");
        if (open.showdialog() == true)
        {
          var path = open.filename;
          //检查图标目录,绝对路径下面
          string newpath = system.environment.currentdirectory + @"\images\tile\group\";
          string newfile = newpath + path.getfilename(path);
          if (!system.io.directory.exists(newpath))
          {
            system.io.directory.createdirectory(newpath);
          }
          file.copy(path, newfile, true); //复制文件到目录绝对路径文件夹
          fileinfo info = new fileinfo(newfile); //新文件
          if (info.length > menuviewmodel.userimagemaxlength)
          {
            messagehelper.showautoclosewarning(string.format("图标不能大于{0}m",
              menuviewmodel.userimagemaxlength / 1024 / 1024));
            return;
          }
          byte[] buf;
          if (!pathtobyte(path, out buf))
          {
            messagehelper.showautoclosewarning("修改失败");
            return;
          }
          imagesource = bytetoimage(buf);
          imagepath = @"\images\tile\group\" + path.getfilename(path); //显示相对路径

        }
      }
      catch (exception ex)
      {

        throw ex;
      }
    }

点击保存的时候再把相对路径保存到数据库rightgroup.imagepath = imagepath;

//公共帮助方法

//把图片文件转换为byte数组
 public static bool pathtobyte(string path, out byte[] buffer)
    {
      filestream fs = new filestream(path, filemode.open, fileaccess.read);
      try
      {
        buffer = new byte[fs.length];
        fs.read(buffer, 0, (int)fs.length);
        return true;
      }
      catch (exception ex)
      {
        buffer = null;
        return false;
      }
      finally
      {
        if (fs != null)
        {
          //关闭资源  
          fs.close();
        }
      }
      
    }

//把byte数组转化为bitmapimage 
    public static bitmapimage bytetoimage(byte[] buf)
    {
      bitmapimage bmp = new bitmapimage();
      bmp.begininit();
      bmp.streamsource = new memorystream(buf);
      bmp.endinit();

      return bmp;
    }

view 界面绑定代码:

<button grid.row="0" grid.column="0" content="选择图片" cm:message.attach="[click]=[changedicon()]" style="{staticresource btnoperationstyle}" height="20" width="70"></button>
          <grid grid.row="0" grid.column="1" background="lightgray">
            <image height="120" width="150" stretch="fill" source="{binding imagesource,mode=twoway, updatesourcetrigger=propertychanged}"></image>
    </grid>
   <label grid.row="1" grid.column="0" style="{staticresource gridcolumnlabelstyle}" content="路径:"></label>
<textbox grid.row="1" grid.column="1" style="{staticresource stylefortextbox}" text="{binding imagepath,mode=twoway,updatesourcetrigger=propertychanged}" height="30" textalignment="center" isreadonly="true"></textbox>

界面效果:

MVVM模式下WPF动态绑定展示图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。