티스토리 뷰

반응형

MainMenuModule의 MainMenuView.xaml 화면에 MVVM Pattern을 적용해서 사용하는 방법을 간단하게 알아 보도록 하겠다.

1. 폴더 추가
Models, ViewModels

2. Models 폴더 추가

MenuModel.cs

using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.ComponentModel;

namespace MainMenuModule.Model
{
    /// <summary>
    /// 메뉴 모델 익스포트
    /// </summary>
    [Export]
    public class MenuModel : IMenuModel, INotifyPropertyChanged
    {
        #region PropertyChange
        public event PropertyChangedEventHandler PropertyChanged;

        public virtual void FirePropertyChange(string PropertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
            }
        }
        #endregion

        ObservableCollection<string> menuCollection;
        /// <summary>
        /// 메뉴 컬렉션
        /// </summary>
        public ObservableCollection<string> MenuCollection
        {
            get { return menuCollection; }
            set
            {
                menuCollection = value;
                FirePropertyChange("MenuCollection");
            }
        }

        /// <summary>
        /// 생성자 - ImportingConstructor가 없으면 기본 생성자로 생성함
        /// </summary>
        public MenuModel()
        {
            MenuCollection = new ObservableCollection<string>();
            MenuCollection.Add("MD");
            MenuCollection.Add("SYS");
            MenuCollection.Add("SALE");
            MenuCollection.Add("WH");
        }

        #region IMenuModel Members

        /// <summary>
        /// 추가
        /// </summary>
        /// <param name="addData"></param>
        public void Adding(object addData)
        {
            if (addData != null && addData is string)
            {
                MenuCollection.Add(addData as string);
            }
        }

        /// <summary>
        /// 취소
        /// </summary>
        public void Canceling()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 조회
        /// </summary>
        /// <param name="Condition"></param>
        public void Getting(string Condition)
        {
            if (Condition.Length == 0)
            {

            }
            else
            {
            }
        }

        string messageData;
        /// <summary>
        /// 메시지
        /// </summary>
        public string MessageData
        {
            get
            {
                return messageData;
            }
            set
            {
                messageData = value;
                FirePropertyChange("MessageData");
            }
        }

        /// <summary>
        /// 삭제
        /// </summary>
        /// <param name="removeData"></param>
        public void Removing(object removeData)
        {
            if (removeData != null && removeData is string)
            {
                MenuCollection.Remove(removeData as string);
            }
        }

        /// <summary>
        /// 저장
        /// </summary>
        public void Saving()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

3. ViewModels 추가

MainMenuViewModel.cs

using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Controls;
using MainMenuModule.Model;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;

namespace PrismMEF1.MainMenuModule.ViewModels
{
    /// <summary>
    /// 뷰 모델 익스포트
    /// </summary>
    [Export]
    public class MainMenuViewModel : NotificationObject
    {
        string messageData;
        /// <summary>
        /// 메시지 데이터
        /// </summary>
        public string MessageData
        {
            get
            {
                return messageData;
            }
            set
            {
                if (messageData != value)
                {
                    messageData = value;
                    //프리즘에서 제공하는 프로퍼티 체인지 이벤트
                    RaisePropertyChanged(() => this.MessageData);
                }
            }
        }

        ObservableCollection<string> messageCollection;
        /// <summary>
        /// 메시지 컬렉션
        /// </summary>
        public ObservableCollection<string> MessageCollection
        {
            get
            {
                return messageCollection;
            }
            set
            {
                if (messageCollection != value)
                {
                    messageCollection = value;
                    RaisePropertyChanged(() => this.MessageCollection);
                }
            }
        }

        private MenuModel mainMenu;
        /// <summary>
        /// 메뉴 모델
        /// </summary>
        public MenuModel MainMenu
        {
            get
            {
                return mainMenu;
            }
            set
            {
                mainMenu = value;
                RaisePropertyChanged(() => this.MainMenu);
            }
        }

        /// <summary>
        /// 임포트 컨트스럭처 - 익스포트/임포트시에 실행되는 생성자
        /// </summary>
        /// <param name="menuModel"></param>
        [ImportingConstructor]
        public MainMenuViewModel(MenuModel menuModel)
        {
            MessageCollection = new ObservableCollection<string>();
            //임포트 받은 메뉴 모델을 프로퍼티에 연결
            this.MainMenu = menuModel;
        }

        /// <summary>
        /// 디자인 타임 생성자
        /// </summary>
        public MainMenuViewModel()
        {
            this.MainMenu = new MenuModel();
        }

        DelegateCommand<object> menuSelect;
        /// <summary>
        /// 메뉴 선택 커맨드
        /// </summary>
        public DelegateCommand<object> MenuSelect
        {
            get
            {
                if (menuSelect == null)
                {
                    menuSelect = new DelegateCommand<object>(obj =>
                    {
                        ListBox lb = obj as ListBox;
                        if (lb != null && lb.SelectedItem != null)
                        {
                            var item = lb.SelectedItem as string;
                            MessageBox.Show(item);
                        }
                    }
                    );
                }

                return menuSelect;
            }
        }

        DelegateCommand<object> menuAdd;
        /// <summary>
        /// 메뉴 추가 커맨드
        /// </summary>
        public DelegateCommand<object> MenuAdd
        {
            get
            {
                if (menuAdd == null)
                {
                    menuAdd = new DelegateCommand<object>(obj =>
                    {
                        var cnt = MainMenu.MenuCollection.Count;
                        var menu = "NewMenu" + cnt.ToString();
                        MainMenu.Adding(menu);
                    }
                    );
                }

                return menuAdd;
            }
        }

        DelegateCommand<object> menuRemove;
        /// <summary>
        /// 메뉴 삭제 커맨드
        /// </summary>
        public DelegateCommand<object> MenuRemove
        {
            get
            {
                if (menuRemove == null)
                {
                    menuRemove = new DelegateCommand<object>(obj =>
                    {
                        ListBox lb = obj as ListBox;
                        if (lb != null && lb.SelectedItem != null)
                        {
                            var menu = lb.SelectedItem as string;
                            MainMenu.Removing(menu);
                        }
                    }
                    );
                }

                return menuRemove;
            }
        }
    }
}

4. MainMenuView.xaml.cs

using System.ComponentModel.Composition;
using System.Windows.Controls;
using PrismMEF1.MainMenuModule.ViewModels;

namespace PrismMEF1.MainMenuModule.Views
{
    [Export(typeof(MainMenuView))]
    public partial class MainMenuView : UserControl
    {
        /// <summary>
        /// 뷰 모델 임포트 - 비동기 동작
        /// </summary>
        [Import]
        public MainMenuViewModel ViewModel
        {
            get { return this.DataContext as MainMenuViewModel; }
            set
            {
                this.DataContext = value;
            }
        }

        /// <summary>
        /// 생성자
        /// </summary>
        public MainMenuView()
        {
            InitializeComponent();
        }
    }
}

5. MainMenuView.xaml

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:PrismMEF1_MainMenuModule_ViewModels="clr-namespace:PrismMEF1.MainMenuModule.ViewModels"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    x:Class="PrismMEF1.MainMenuModule.Views.MainMenuView"
    FontSize="18"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
   
    <!--디자인 타임에 뷰 모델을 사용하기 위해서 입력-->
 <d:DataContext>
  <PrismMEF1_MainMenuModule_ViewModels:MainMenuViewModel/>
 </d:DataContext>

   
    <StackPanel x:Name="LayoutRoot" Background="Blue">
     <Button Content="Main Menu Add" Foreground="#FF1F257E" >
      <i:Interaction.Triggers>
       <i:EventTrigger EventName="Click">
        <i:InvokeCommandAction Command="{Binding MenuAdd, Mode=OneWay}"/>
       </i:EventTrigger>
      </i:Interaction.Triggers>
     </Button>
     <Button Content="Main Menu Remove" Foreground="#FF1F257E">
      <i:Interaction.Triggers>
       <i:EventTrigger EventName="Click">
        <i:InvokeCommandAction Command="{Binding MenuRemove, Mode=OneWay}" CommandParameter="{Binding ElementName=listBox}"/>
       </i:EventTrigger>
      </i:Interaction.Triggers>
     </Button>
        <ListBox x:Name="listBox" ItemsSource="{Binding MainMenu.MenuCollection}">
         <i:Interaction.Triggers>
          <i:EventTrigger EventName="SelectionChanged">
           <i:InvokeCommandAction Command="{Binding MenuSelect, Mode=OneWay}" CommandParameter="{Binding ElementName=listBox}"/>
          </i:EventTrigger>
         </i:Interaction.Triggers>
        </ListBox>
    </StackPanel>
</UserControl>

6. 실행

1) 시작

2) Main Menu Add 버튼 클릭으로 메뉴 추가


3) Main Menu Remove 버튼 클릭으로 메뉴 삭제

7. 자세한 사항은 소스를 참고 하기 바란다.

PrismMEF1 (2).zip
다운로드


 

반응형
댓글