WPF dynamic binding display picture in MVVM mode

Time:2021-7-16

In MVVM mode, WPF dynamically displays pictures, selects icons in the interface, copies them to the fixed directory of the project, saves them to the database by relative path, and reads them again by relative path of the database to obtain pictures of absolute path in the project.

First, in ViewModel

//Attribute definition
    BitmapImage _ImageSource;
    /// <summary>
    ///Icons displayed
    /// </summary>
    public BitmapImage ImageSource
    {
      get { return _ImageSource; }
      set
      {
        _ImageSource = value;
        NotifyOfPropertyChange("ImageSource");
      }
    }

    string _ImagePath;
    /// <summary>
    ///Icons displayed路径
    /// </summary>
    public string ImagePath
    {
      get { return _ImagePath; }
      set
      {
        _ImagePath = value;
        NotifyOfPropertyChange("ImagePath");
      }
    }
//Initialization data
//Binding data when editing
public GroupInfoViewModel(sys_Right_Group groupInfo, OperType type)
    {
      if (type == OperType.Edit || type == OperType.Show)
      {
        IsAdd = false;
        Titlename = edit group;
        RightGroup = groupInfo;
        ImagePath = groupInfo.ImagePath; 
        GetImgData(groupInfo.ImagePath);
      }
    }
    /// <summary>
    ///Get image 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 the absolute path of the file
        byte[] buf;
        if (!PathToByte(fileName, out buf))
        {
          Message helper. Showautoclosewarning ("failed to get icon");
          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, under the absolute path
          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 files to directory absolute path folder
          FileInfo info = new FileInfo(newFile); // new file
          if (info.Length > MenuViewModel.UserImageMaxLength)
          {
            Message helper.showautoclosewarning (string. Format ("icon cannot be larger than {0} m"),
              MenuViewModel.UserImageMaxLength / 1024 / 1024));
            return;
          }
          byte[] buf;
          if (!PathToByte(path, out buf))
          {
            Message helper.showautoclosewarning ("modification failed");
            return;
          }
          ImageSource = ByteToImage(buf);
          ImagePath = @"\Images\Tile\Group\" + Path.GetFileName(path); // Show relative paths

        }
      }
      catch (Exception ex)
      {

        throw ex;
      }
    }

Click Save to save the relative path to the database rightgroup. Imagepath = imagepath;

//Public help methods

//Convert image file to byte array
 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)
        {
          //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] = [changeicon()] "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 =" path: > < / 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>

Interface effect:

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

Talk about spring Kafka’s retry

order This article mainly talks about the retry of spring for Kafka AbstractRetryingMessageListenerAdapter spring-kafka-1.2.3.RELEASE-sources.jar!/org/springframework/kafka/listener/adapter/AbstractRetryingMessageListenerAdapter.javaThere are two main implementation classes: retryingacknowledgingmessagelisteneradapter and retryingmessagelisteneradapter RetryingAcknowledgingMessageListenerAdapter public class RetryingAcknowledgingMessageListenerAdapter<K, V> extends AbstractRetryingMessageListenerAdapter<K, V, AcknowledgingMessageListener<K, V>> implements AcknowledgingMessageListener<K, V> { private final AcknowledgingMessageListener<K, V> delegate; /** * Construct an instance with the provided template and delegate. The exception will […]