ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • WPF ICommand 구현 실습 MVVM
    프로그래밍/C# 2019. 11. 3. 08:02
    반응형

    앞에 내용은 INotifyPropertyChanged 포스팅을 이용해 주세요.

    https://magpienote.tistory.com/52

    ICommand는 MVVM패턴에서 ViewModel단에서 

    사용자 정의 함수를 구현하기 위해서

    정의 해 놓는 곳입니다.

    먼저 필요한게 구현한 내용과

    delegate를 이용한 ICommand를 구현해 놓는 것입니다.

    소스를 보시죠.

     

    public class ViewModel : Notifier
        {
            string title = "D-day를 새볼까요?";
            public string Title
            {
                get { return title; }
                set
                {
                    title = value;
                    OnPropertyChanged("Title");
                }
            }
            int num = 0;
            public int Num
            {
                get { return num; }
                set
                {
                    num = value;
                    OnPropertyChanged("Num");
                }
            }
            private ICommand checkCommand;
            public ICommand CheckCommand
            {
                get { return (this.checkCommand) ?? (this.checkCommand = new DelegateCommand(Check)); }
            }
    
    
            private void Check()
            {
                num++;
                OnPropertyChanged("Num");
            }
    
        }
    
        public class DelegateCommand : ICommand
        {
    
            private readonly Func<bool> canExecute;
            private readonly Action execute;
    
            /// <summary>
            /// Initializes a new instance of the DelegateCommand class.
            /// </summary>
            /// <param name="execute">indicate an execute function</param>
            public DelegateCommand(Action execute) : this(execute, null)
            {
            }
    
            /// <summary>
            /// Initializes a new instance of the DelegateCommand class.
            /// </summary>
            /// <param name="execute">execute function </param>
            /// <param name="canExecute">can execute function</param>
            public DelegateCommand(Action execute, Func<bool> canExecute)
            {
                this.execute = execute;
                this.canExecute = canExecute;
            }
            /// <summary>
            /// can executes event handler
            /// </summary>
            public event EventHandler CanExecuteChanged;
    
            /// <summary>
            /// implement of icommand can execute method
            /// </summary>
            /// <param name="o">parameter by default of icomand interface</param>
            /// <returns>can execute or not</returns>
            public bool CanExecute(object o)
            {
                if (this.canExecute == null)
                {
                    return true;
                }
                return this.canExecute();
            }
    
            /// <summary>
            /// implement of icommand interface execute method
            /// </summary>
            /// <param name="o">parameter by default of icomand interface</param>
            public void Execute(object o)
            {
                this.execute();
            }
    
            /// <summary>
            /// raise ca excute changed when property changed
            /// </summary>
            public void RaiseCanExecuteChanged()
            {
                if (this.CanExecuteChanged != null)
                {
                    this.CanExecuteChanged(this, EventArgs.Empty);
                }
            }
        }
      
      

    ViewModel단의 내용입니다. Delegate는 그냥 복사 붙여 넣기 하시면됩니다.

    private ICommand checkCommand;
    public ICommand CheckCommand
    {
    	get { return (this.checkCommand) ?? (this.checkCommand = new DelegateCommand(Check)); }
    }
    
    
    private void Check()
    {
    	num++;
    	OnPropertyChanged("Num");
    }

    ICommand의 이름을 정의하고 그곳에 

    getter를 구현해 놉니다. 그값이 delegate로 이어져 

    check를 실행 시키는 구조 입니다.

    <Window x:Class="Wpf_INotified.MainWindow"
            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:local="clr-namespace:Wpf_INotified"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Grid>
            <TextBlock Text="{Binding Title}" HorizontalAlignment="Left" Margin="148,58,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="23"/>
            <TextBlock Text="{Binding Num}" HorizontalAlignment="Left" Margin="148,103,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
            <TextBox Text="{Binding Path=Num, Mode=TwoWay}" HorizontalAlignment="Left" Height="23" Margin="364,58,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120"/>
            <TextBox Text="참조" HorizontalAlignment="Left" Height="23" Margin="364,103,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120"/>
            <Button Command="{Binding CheckCommand}" Content="Button" HorizontalAlignment="Left" Margin="364,151,0,0" VerticalAlignment="Top" Width="75"/>
        </Grid>
        
    </Window>
    

    View단에서 Button을 하나 만들어 줍니다.

    그리고 바인딩을 CheckCommand로 이어 줍니다.

    참 쉽네요.

    첫번째 실행 화면

     

    버튼을 클릭한 화면

     

     

    이렇게 실습을 해보았습니다.

    실제로 MVVM패턴을 구체화 시켜 

    구현해놓은 

    것을 포스팅 해 놓겠습니다. 

    위에 포스팅들을 보시고

    연습을 하시고 연습한다음.

    이 포스팅을 보시고 

    MVVM패턴의 구조를 확실히 

    익히 시기 바랍니다.

    https://magpienote.tistory.com/51

    반응형

    댓글

Designed by Tistory.