2017/02/05

WPF(Prism)で画像の表示

Prismを利用したWPFアプリケーションで、選択した画像を表示するプログラムを作成します。

実際に作ったのは下図で、このような機能があります。
①Openボタンでファイル選択ダイヤログが開き、jpgファイルを選択する
②TextBoxにファイルのパスが表示される
③画像が下に表示される


まず、NuGetで「Prism.MVVM」をインストールしておいてください。
プロジェクトでは下図のように3つのフォルダでMVVMごとに管理しています。


 まず、DisplayImageWindow.xamlは以下のようになります。

    
        
        

次に、DisplayImageWindowViewModelは以下のようになります。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;
using DisplayImage.Model;

using System.Windows.Media.Imaging;

namespace DisplayImage.ViewModel
{
    class DisplayImageWindowViewModel: BindableBase
    {
        public DisplayImageWindowViewModel()
        {
            Displayer = new ImageDisplayer();
        }

        ImageDisplayer Displayer;

        //=================
        //Change Property
        //=================
        private string filePath;
        public string FilePath
        {
            get { return filePath; }
            set { SetProperty(ref filePath, value); }
        }

        private BitmapImage bmp;
        public BitmapImage Bmp
        {
            get { return bmp; }
            set { SetProperty(ref bmp, value); }
        }

        //=================
        //DeligateCommand
        //=================
        private DelegateCommand fileOpenCommand;
        public DelegateCommand FileOpenCommand
        {
            get { return fileOpenCommand ?? (fileOpenCommand = new DelegateCommand(FileOpen)); }
        }
        public void FileOpen()
        {
            Displayer.FileOpen();

            FilePath = Displayer.FilePath;
            Bmp = Displayer.Bmp;
        }
    }
}


最後にImageDisplayerです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Win32;
using System.Windows.Media.Imaging;

namespace DisplayImage.Model
{
    class ImageDisplayer
    {
        public ImageDisplayer()
        {
        }

        public string FilePath { get; set; }
        public BitmapImage Bmp;

        public void FileOpen()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open Image File.";
            dlg.Filter = "Image File|*.jpg";

            if (dlg.ShowDialog() == true)
            {
                FilePath = dlg.FileName;

                Bmp = new BitmapImage();
                Bmp.BeginInit();
                Bmp.UriSource = new Uri(FilePath);
                Bmp.EndInit();

            }
        }
    }
}


0 件のコメント:

コメントを投稿