WPF, XAML

WPF Command 패턴, 데이터바인딩 실습예제

오라클왕 0 21 10.29 11:47

WPF Command 패턴, 데이터바인딩  실습예제

 

[실행화면]


[Emp.cs]

namespace CommandExam

{

    class Emp

    {

        public string Ename { get; set; }

        public string Job { get; set; }

        public override string ToString()

        {

            return "[" + Ename + "," + Job + "]";

        }

    }

}

 

[RelayCommand.cs]

using System;

using System.Windows.Input;

namespace CommandExam

{

    class RelayCommand : ICommand

    {

        #region Variables

        Func<object, bool> canExecute;

        Action<object> executeAction;

        #endregion

        #region Construction/Initialization

        public RelayCommand(Action<object> executeAction) :

       this(executeAction, null)

        {

        }

        public RelayCommand(Action<object> executeAction, Func<object, bool>

       canExecute)

        {

            this.executeAction = executeAction ?? throw new

           ArgumentNullException("Execute Action was null for ICommanding Operation.");

            this.canExecute = canExecute;

        }

        #endregion

        #region ICommand Member

        public bool CanExecute(object param)

        {

            // 사원이름을 입력하지 않으면 Add 버튼은 비활성화 된다.

            if (param?.ToString().Length == 0) return false;

            bool result = this.canExecute == null ? true :

           this.canExecute.Invoke(param);

            return result;

        }

        public void Execute(object param)

        {

            //System.Windows.MessageBox.Show(param.ToString());

            this.executeAction.Invoke(param);

        }

        public event EventHandler CanExecuteChanged

        {

            add { CommandManager.RequerySuggested += value; }

            remove { CommandManager.RequerySuggested -= value; }

        }

        #endregion

    }

}

 


[MainWindowViewModel.cs]

using System.Collections.ObjectModel;

using System.ComponentModel;

using System.Runtime.CompilerServices;

namespace CommandExam

{

    class MainWindowViewModel : INotifyPropertyChanged

    {

        public Emp _SelectedEmp;

        public Emp SelectedEmp

        {

            get

            {

                return _SelectedEmp;

            }

            set

            {

                _SelectedEmp = value;

                OnPropertyChanged("SelectedEmp");

            }

        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string

Pname = null)

        {

            PropertyChanged?.Invoke(this, new

           PropertyChangedEventArgs(Pname));

        }

        public RelayCommand AddEmpCommand { get; set; }

        public ObservableCollection<Emp> Emps { get; set; }

        public MainWindowViewModel()

        {

            Emps = new ObservableCollection<Emp>();

            Emps.Add(new Emp { Ename = "홍길동", Job = "Salesman" });

            Emps.Add(new Emp { Ename = "김길동", Job = "Clerk" });

            Emps.Add(new Emp { Ename = "정길동", Job = "Manager" });

            Emps.Add(new Emp { Ename = "박길동", Job = "Salesman" });

            Emps.Add(new Emp { Ename = "성길동", Job = "Clerk" });

            AddEmpCommand = new RelayCommand(AddEmp);

        }

        public void AddEmp(object param)

        {

            Emps.Add(new Emp { Ename = param.ToString() });

        }

    }

}



[MainWindow.xaml.cs]
<Window x:Class="CommandExam.MainWindow"
        xmlns:local="clr-namespace:CommandExam"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
    <StackPanel>
        <TextBlock>사원 이름을 입력하세요.</TextBlock>
        <TextBox x:Name="txtName"/>
        <Button Command="{Binding AddEmpCommand}"
CommandParameter="{Binding Text, ElementName=txtName}">Add</Button>
        <ListBox ItemsSource="{Binding Emps}" 
                 SelectedItem="{Binding SelectedEmp}"
                 DisplayMemberPath="Ename"
                 x:Name="empListBox"/>
        <Label x:Name="label" Content="{Binding SelectedItem, ElementName=empListBox}" 
               HorizontalAlignment="Center" 
               Height="40" 
               Margin="10,0,0,0" Width="137"              />
    </StackPanel>
</Window>



[MainWindow.xaml.cs]
using System.Windows;

namespace CommandExam
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}


 

Comments