這篇文章主要為大家詳細介紹了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>
介面效果: