Instance analysis of WPF dynamic display picture in MVVM mode

Source: Internet
Author: User
This article is mainly for you in detail the MVVM mode WPF dynamic binding display image of the relevant data, with a certain reference value, interested in small partners can refer to

In the MVVM mode WPF dynamic display picture, interface selection icon, copied to the project under the fixed directory, save to the database is a relative path, again read the time is based on the relative path of the database to get the absolute path of the project image display.

First, in the ViewModel.

Attribute definition    BitmapImage _imagesource;    <summary>////Display icons///    </summary> public    BitmapImage imagesource    {      Get {return _ _ ImageSource; }      set      {        _imagesource = value;        Notifyofpropertychange ("ImageSource");      }    }    string _imagepath;    <summary>////    Display the icon Path///    </summary> public    string ImagePath    {      Get {return _ _ ImagePath; }      set      {        _imagepath = value;        Notifyofpropertychange ("ImagePath");      }    }
//initialize data//edit bind Data public Groupinfoviewmodel (Sys_right_group groupinfo, Opertype type) {        if (type = = Opertype.edit | | type = = opertype.show) {Isadd = false;        TitleName = "Edit Grouping";        Rightgroup = GroupInfo;         ImagePath = Groupinfo.imagepath;      Getimgdata (Groupinfo.imagepath);    }}///<summary>///Get Picture data///</summary>//<param name= "Imgpath" > Relative path </param> private void Getimgdata (string imgpath) {if (string.      IsNullOrEmpty (Imgpath)) return;        try {string fileName = System.Environment.CurrentDirectory + imgpath;//Get absolute path to file byte[] buf; if (!          Pathtobyte (FileName, out buf)) {messagehelper.showautoclosewarning ("Get icon failed");        Return      } imagesource =bytetoimage (BUF);      } catch (Exception ex) {throw ex; }    }
Interface Select Picture button Event///<summary>//Modify picture///</summary> public void Changedicon () {try {        OpenFileDialog open = new OpenFileDialog (); Open. Filter = string.        Format ("Photo |*.jpg;*.jpeg;*.png;*.gif;*.bmp"); if (open. ShowDialog () = = true) {var path = open.          FileName;          Check the icon directory, the absolute path below the 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); Copy file to directory absolute path folder FileInfo info = new FileInfo (newFile); The new file if (info. Length > Menuviewmodel.userimagemaxlength) {messagehelper.showautoclosewarning (string.            Format ("icon cannot be greater than {0}m", menuviewmodel.userimagemaxlength/1024/1024));          Return } byte[]Buf if (!            Pathtobyte (path, out buf)) {messagehelper.showautoclosewarning ("failed to modify");          Return          } ImageSource = Bytetoimage (BUF); ImagePath = @ "\images\tile\group\" + path.getfilename (Path);      Show relative Path}} catch (Exception ex) {throw ex; }    }

Click Save to save the relative path to the database Rightgroup.imagepath = ImagePath;

Public Help method//Convert picture file to byte array public static bool Pathtobyte (string path, out byte[] buffer)    {      FileStream fs = new files Tream (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)        {          //close resource            fs. Close ();}}          } Convert byte array to BitmapImage public     static BitmapImage bytetoimage (byte[] buf)    {      BitmapImage bmp = new BitmapImage ();      Bmp. BeginInit ();      Bmp. Streamsource = new MemoryStream (BUF);      Bmp. EndInit ();      return bmp;    }

View Interface Binding Code:

<button grid.row= "0" grid.column= "0" content= "Select Picture" Cm:message.attach= "[Click]=[changedicon ()]" Style= "{ StaticResource Btnoperationstyle} "height=" width= "></Button>          <grid grid.row=" 0 "grid.column= "1" background= "Lightgray" >            <image height= "All" width= "stretch=" "Fill" source= "{Binding imagesource, Mode=twoway, updatesourcetrigger=propertychanged} "></Image>    </Grid>   <label grid.row=" 1 "grid.column=" 0 "style=" {StaticResource gridcolumnlabelstyle} "content=" path: "></label><textbox Grid.Row = "1" grid.column= "1" style= "{StaticResource stylefortextbox}" text= "{Binding imagepath,mode=twoway, updatesourcetrigger=propertychanged} "height=" "textalignment=" Center "isreadonly=" True "></TextBox>

Interface effect:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.