■ MVVM 패턴 사용하기

----------------------------------------------------------------------------------------------------

▶ System.Windows.Interactivity 참조를 추가한다.

 

RelayCommand.cs

 

using System;

using System.Windows.Input;

 

namespace TestProject

{

    /// <summary>

    /// 릴레이 명령

    /// </summary>

    public class RelayCommand : ICommand

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Event

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 실행 가능 여부 변경시 - CanExecuteChanged

 

        /// <summary>

        /// 실행 가능 여부 변경시

        /// </summary>

        public event EventHandler CanExecuteChanged

        {

            add

            {

                CommandManager.RequerySuggested += value;

            }

            remove

            {

                CommandManager.RequerySuggested -= value;

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 실행 액션

        /// </summary>

        private readonly Action<object> executeAction;

 

        /// <summary>

        /// 실행 가능 여부 프레디킷

        /// </summary>

        private readonly Predicate<object> canExecutePredicate;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - RelayCommand(executeAction, canExecutePredicate)

 

        /// <summary>

        /// 생성자

        /// </summary>

        /// <param name="executeAction">실행 액션</param>

        /// <param name="canExecutePredicate">실행 가능 여부 프레디킷</param>

        public RelayCommand(Action<object> executeAction, Predicate<object> canExecutePredicate)

        {

            if(executeAction == null)

            {

                throw new ArgumentNullException("executeAction");

            }

 

            this.executeAction       = executeAction;

            this.canExecutePredicate = canExecutePredicate;

        }

 

        #endregion

 

        #region 생성자 - RelayCommand(executeAction)

 

        /// <summary>

        /// 생성자

        /// </summary>

        /// <param name="executeAction">실행 액션</param>

        public RelayCommand(Action<object> executeAction) : this(executeAction, null)

        {

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 실행하기 - Execute(parameter)

 

        /// <summary>

        /// 실행하기

        /// </summary>

        /// <param name="parameter">파라미터</param>

        public void Execute(object parameter)

        {

            this.executeAction(parameter);

        }

 

        #endregion

 

        #region 실행 가능 여부 구하기 - CanExecute(parameter)

 

        /// <summary>

        /// 실행 가능 여부 구하기

        /// </summary>

        /// <param name="parameter">파라미터</param>

        /// <returns>실행 가능 여부</returns>

        public bool CanExecute(object parameter)

        {

            return this.canExecutePredicate == null ? true : this.canExecutePredicate(parameter);

        }

 

        #endregion

    }

}

 

Employee.cs

 

namespace TestProject

{

    /// <summary>

    /// 직원

    /// </summary>

    public class Employee

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 사번 - EmployeeID

 

        /// <summary>

        /// 사번

        /// </summary>

        public int EmployeeID {  get; set; }

 

        #endregion

 

        #region 이름 - FirstName

 

        /// <summary>

        /// 이름

        /// </summary>

        public string FirstName { get; set; }

 

        #endregion

 

        #region 성 - LastName

 

        /// <summary>

        ///

        /// </summary>

        public string LastName { get; set; }

 

        #endregion

 

        #region 부서 - Department

 

        /// <summary>

        /// 부서

        /// </summary>

        public string Department { get; set; }

 

        #endregion

 

        #region 직함 - Title

 

        /// <summary>

        /// 직함

        /// </summary>

        public string Title { get; set; }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 문자열 구하기 - ToString()

 

        /// <summary>

        /// 문자열 구하기

        /// </summary>

        /// <returns>문자열</returns>

        public override string ToString()

        {

            return string.Format("{0} {1} ({2})", FirstName, LastName, EmployeeID);

        }

 

        #endregion

    }

}

 

MainWindow.xaml

 

<Window

    x:Class="TestProject.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

    Width="300"

    Height="250"

    MinHeight="200"

    Title="메인 윈도우">

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="110px" />

            <RowDefinition Height="*"     />

        </Grid.RowDefinitions>

        <ListBox Name="employeeListBox"

            ItemsSource="{Binding EmployeeList}"

            SelectedItem="{Binding SelectedEmployee}">

            <i:Interaction.Triggers>

                <i:EventTrigger EventName="SelectionChanged">

                    <i:InvokeCommandAction

                        Command="{Binding SelectionChangedCommand}"

                        CommandParameter="{Binding ElementName=employeeListBox, Path=SelectedValue}" />

                </i:EventTrigger>

            </i:Interaction.Triggers>

        </ListBox>

        <Grid

            Grid.Row="1"

            DataContext="{Binding SelectedEmployee}">

            <Grid.RowDefinitions>

                <RowDefinition Height="*" />

                <RowDefinition Height="*" />

                <RowDefinition Height="*" />

                <RowDefinition Height="*" />

            </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>

                <ColumnDefinition Width="80" />

                <ColumnDefinition Width="*" />

            </Grid.ColumnDefinitions>

                <Label Grid.Row="0" Grid.Column="0">First Name</Label>

                <Label Grid.Row="1" Grid.Column="0">Last Name</Label>

                <Label Grid.Row="2" Grid.Column="0">Title</Label>

                <Label Grid.Row="3" Grid.Column="0">Department</Label>

                <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=FirstName , Mode=TwoWay}" />

                <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=LastName , Mode=TwoWay}" />

                <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=Title     , Mode=TwoWay}" />

                <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding Path=Department, Mode=TwoWay}" />

            </Grid>

    </Grid>

</Window>

 

MainWindow.xaml.cs

 

using System.Windows;

 

namespace TestProject

{

    /// <summary>

    /// 메인 윈도우

    /// </summary>

    public partial class MainWindow : Window

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainWindow()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainWindow()

        {

            InitializeComponent();

 

            DataContext = new MainWindowViewModel();

        }

 

        #endregion

    }

}

 

MainWindowViewModel.cs

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

 

namespace TestProject

{

    /// <summary>

    /// 메인 윈도우 뷰 모델

    /// </summary>

    public class  MainWindowViewModel : INotifyPropertyChanged

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Event

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 속성 변경시 - PropertyChanged

 

        /// <summary>

        /// 속성 변경시

        /// </summary>

        public event PropertyChangedEventHandler PropertyChanged;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 직원 리스트

        /// </summary>

        private List<Employee> employeeList = null;

 

        /// <summary>

        /// 선택 직원

        /// </summary>

        private Employee selectedEmployee = null;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 직원 리스트 - EmployeeList

 

        /// <summary>

        /// 직원 리스트

        /// </summary>

        public List<Employee> EmployeeList

        {

            get

            {

                return this.employeeList;

            }

            set

            {

                if(this.employeeList == value)

                {

                    return;

                }

 

                this.employeeList = value;

 

                OnPropertyChanged("EmployeeList");

            }

        }

 

        #endregion

 

        #region 선택 직원 - SelectedEmployee

 

        /// <summary>

        /// 선택 직원

        /// </summary>

        public Employee SelectedEmployee

        {

            get

            {

                return this.selectedEmployee;

            }

            set

            {

                if(this.selectedEmployee == value)

                {

                    return;

                }

 

                this.selectedEmployee = value;

 

                OnPropertyChanged("SelectedEmployee");

            }

        }

 

        #endregion

 

 

        #region 선택 변경시 명령 - OnSelectionChangedCommand

 

        /// <summary>

        /// 선택 변경시 명령

        /// </summary>

        public RelayCommand OnSelectionChangedCommand { get; set; }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainWindowViewModel()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainWindowViewModel()

        {

            List<Employee> employeeList = new List<Employee>();

 

            employeeList.Add(new Employee() { EmployeeID = 1, FirstName = "John", LastName = "Dow", Title = "Accountant", Department = "Payroll" });

            employeeList.Add(new Employee() { EmployeeID = 2, FirstName = "Jane", LastName = "Austin", Title = "Account Executive", Department = "Employee Management" });

            employeeList.Add(new Employee() { EmployeeID = 3, FirstName = "Ralph", LastName = "Emmerson", Title = "QA Manager", Department = "Product Development" });

            employeeList.Add(new Employee() { EmployeeID = 4, FirstName =  "Patrick", LastName = "Fitzgerald", Title = "QA Manager", Department = "Product Development" });

            employeeList.Add(new Employee() { EmployeeID = 5, FirstName =  "Charles", LastName = "Dickens", Title = "QA Manager", Department = "Product Development" });

 

            EmployeeList = employeeList;

 

            OnSelectionChangedCommand = new RelayCommand(OnSelectionChanged);

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 선택 변경시 처리하기 - OnSelectionChanged(parameter)

 

        /// <summary>

        /// 선택 변경시 처리하기

        /// </summary>

        /// <param name="parameter">파라미터</param>

        public void OnSelectionChanged(object parameter)

        {

            SelectedEmployee = parameter as Employee;

        }

 

        #endregion

 

        ////////////////////////////////////////////////////////////////////////////////////////// Protected

 

        #region 속성 변경시 처리하기 - OnPropertyChanged(propertyName)

 

        /// <summary>

        /// 속성 변경시 처리하기

        /// </summary>

        /// <param name="propertyName">속성명</param>

        protected void OnPropertyChanged(string propertyName)

        {

            if(PropertyChanged != null)

            {

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }

        }

 

        #endregion

    }

}

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요