View에서 특정 이벤트가 발생할 때 특정 동작을 하고싶을때에는 System.Windows.Interactivity 네임스페이스의 Interaction Class를 이용하여 ICommand 개체에 바인딩하였습니다.

 만약 특정 컨트롤에서 MouseDown 이벤트가 발생할때 이벤트 매개변수인 MouseButtonEventArgs 개체를 넘겨주고 싶다면 Galasoft의 EventToCommand Class를 이용하여 쉽게 구현 할 수 있습니다.

 

 

 Galasoft.MvvmLight.WPF4 툴킷이 있다는 가정하에 설명하겠습니다.

 우선 View의 xaml 코드에서 두개의 네임스페이스를 등록합니다.

 

 

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

       xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4" 

 

 

 

 

 저는 테스트를 위해 Window가 Loaded 되었을 때와 MouseDown 되었을 때 ICommand 개체를 바인딩하였습니다.

 MouseDown 이벤트가 발생하였을 때에는 MouseButtonEventArgs 이벤트를 매개변수로 넘기기 위해 PassEventArgsToCommand 속성을 True로 하였습니다. 이때에는 ICommand 매개변수가 꼭 MouseButtonEventArgs여야만 합니다.

 

 

   <i:Interaction.Triggers>

        <i:EventTrigger EventName="Loaded">

            <i:InvokeCommandAction Command="{Binding CmdLoaded, Mode=OneWay}" CommandParameter="Loaded!"/>

        </i:EventTrigger>

        <i:EventTrigger EventName="MouseDown">

            <cmd:EventToCommand Command="{Binding CmdMouseDown, Mode=OneWay}" MustToggleIsEnabledValue="True"  PassEventArgsToCommand="True"/>

        </i:EventTrigger>

    </i:Interaction.Triggers>

 

 

 

 

 ViewModel 코드입니다. 두개의 커맨드 모두 메세지 박스로 데이터를 보여주고 있습니다.

 

 

       private RelayCommand<string> _cmdLoaded;

 

        public RelayCommand<string> CmdLoaded

        {

            get

            {

                if (_cmdLoaded == null)

                    _cmdLoaded = new RelayCommand<string>(a =>

                        MessageBox.Show(a));

                return _cmdLoaded;

            }

        }

 

        private RelayCommand<MouseButtonEventArgs> _cmdMouseDown;

 

        public RelayCommand<MouseButtonEventArgs> CmdMouseDown

        {

            get

            {

                if (_cmdMouseDown == null)

                    _cmdMouseDown = new RelayCommand<MouseButtonEventArgs>(a =>

                        MessageBox.Show(a.MouseDevice.GetPosition(a.OriginalSource as IInputElement).ToString()));

                return _cmdMouseDown;

            }

        }

 

 

 

 프로젝트 첨부하였습니다.

 

AboutEventToCommand.zip

 

 

 

 

 

+ Recent posts