첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
------------------------------------------------------------------------------------------------------------------------------------------------------
728x90
728x170

TestProject.zip
다운로드

▶ 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
    }
}

 

728x90

 

▶ 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="800"
    Height="600"
    Title="MVVM 패턴 사용하기"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Grid Margin="10">
        <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>

 

300x250

 

▶ 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.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;

                FirePropertyChangedEvent("EmployeeList");
            }
        }

        #endregion
        #region 선택 직원 - SelectedEmployee

        /// <summary>
        /// 선택 직원
        /// </summary>
        public Employee SelectedEmployee
        {
            get
            {
                return this.selectedEmployee;
            }
            set
            {
                if(this.selectedEmployee == value)
                {
                    return;
                }

                this.selectedEmployee = value;

                FirePropertyChangedEvent("SelectedEmployee");
            }
        }

        #endregion
        #region 선택 변경시 명령 - SelectionChangedCommand
 
        /// <summary>
        /// 선택 변경시 명령
        /// </summary>
        public RelayCommand SelectionChangedCommand { 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      = "Accountant 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;

            SelectionChangedCommand = new RelayCommand(SelectionChangedCommand_Executed);
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 선택 변경시 명령 실행시 처리하기 - SelectionChangedCommand_Executed(parameter)

        /// <summary>
        /// 선택 변경시 명령 실행시 처리하기
        /// </summary>
        /// <param name="parameter">매개 변수</param>
        public void SelectionChangedCommand_Executed(object parameter)
        {
            SelectedEmployee = parameter as Employee;
        }

        #endregion

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

        #region 속성 변경시 이벤트 발생시키기 - FirePropertyChangedEvent(propertyName)

        /// <summary>
        /// 속성 변경시 이벤트 발생시키기
        /// </summary>
        /// <param name="propertyName">속성명</param>
        protected void FirePropertyChangedEvent(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}
728x90
그리드형(광고전용)
Posted by icodebroker
,