//xaml <Image Grid.Column="1" ClipToBounds="True" Source="{Binding SelectedItem.ImgUrl,ElementName=lbx}"> <Image.ContextMenu> <ContextMenu> <MenuItem Header="Save As Picture"> <behavior:Interaction.Triggers> <behavior:EventTrigger EventName="Click"> <behavior:CallMethodAction TargetObject="{Binding}" MethodName="SaveAsImageClick"/> </behavior:EventTrigger> </behavior:Interaction.Triggers> </MenuItem> <MenuItem Header="Save As String"> <behavior:Interaction.Triggers> <behavior:EventTrigger EventName="Click"> <behavior:CallMethodAction TargetObject="{Binding}" MethodName="SaveAsStringClick"/> </behavior:EventTrigger> </behavior:Interaction.Triggers> </MenuItem> </ContextMenu> </Image.ContextMenu> //cs public void SaveAsImageClick(object sender,EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Image Files|*.jpg;*.png;|All Files|*.*"; if (sfd.ShowDialog() == true && SelectedBook != null) { using(FileStream fs=new FileStream(sfd.FileName,FileMode.OpenOrCreate)) { var bytes = File.ReadAllBytes(SelectedBook.ImgUrl); fs.Write(bytes,0,bytes.Count()); } } } public void SaveAsStringClick(object sender,EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Text Files|*.txt*|All Files|*.*"; if(sfd.ShowDialog()==true && SelectedBook!=null) { var imgUrl = System.IO.Path.GetFullPath(SelectedBook.ImgUrl); string str = ConvertImgToString(imgUrl); File.WriteAllText(sfd.FileName, str); } } private string ConvertImgToString(string imgFullUrl) { if(File.Exists(imgFullUrl)) { byte[] bytes = File.ReadAllBytes(imgFullUrl); string base64Str = Convert.ToBase64String(bytes); return base64Str; } return string.Empty; }
标签:Files,string,MVVM,SelectedBook,bytes,File,MenuItem,WPF,sfd From: https://www.cnblogs.com/Fred1987/p/18287698