2014-01-19 32 views
0

我需要將此事件從用戶控件移動到viewModel,我已閱讀以下鏈接 ,但不知道我得到它,因爲命令是true或false,我的問題是假設我有以下事件 我應該如何將其更改爲viewModel。從用戶控制更改以下事件viewModel

請協助,我真的卡住了!

http://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/

 private void DropText_PreviewMouseDown(object sender, MouseButtonEventArgs e) 
    { 
     var textBox = (TextBox) sender; 
     if (textBox == null) return; 
     textBox.Focus(); 
     var dataObject = new DataObject((textBox).Text); 
     dataObject.SetData(DragSource, sender); 
     DragDrop.DoDragDrop(textBox, dataObject, DragDropEffects.Copy | DragDropEffects.Move); 
    } 



    <TextBox x:Name="Job" 
        AcceptsReturn="True" 
        AllowDrop="True" 
        PreviewMouseDown="DropText_PreviewMouseDown" 
        SelectionChanged="listbox_SelectionChanged" 
        HorizontalAlignment="Left" 





internal class RelayCommand : ICommand 
{ 
    readonly Action _execute; 
    readonly Func<bool> _canExecute; 

    public RelayCommand(Action execute) 
     : this(execute, null) 
    { 
    } 

    public RelayCommand(Action execute, Func<bool> canExecute) 
    { 
     if (execute == null) 
      throw new ArgumentNullException("execute"); 
     _execute = execute; 
     _canExecute = canExecute; 
    } 

    public bool CanExecute(object parameter) 
    { 
     return _canExecute == null ? true : _canExecute(); 
    } 

    public event EventHandler CanExecuteChanged 
    { 
     add 
     { 
      if (_canExecute != null) 
       CommandManager.RequerySuggested += value; 
     } 
     remove 
     { 
      if (_canExecute != null) 
       CommandManager.RequerySuggested -= value; 
     } 
    } 

    public void Execute(object parameter) 
    { 
     _execute(); 
    } 

    public event EventHandler CanExecuteChange; 
    public void RaiseCanExecuteChange() 
     { 
     if (CanExecuteChange != null) 
      CanExecuteChange(this, new EventArgs()); 
     } 
+0

您可以使用在您發佈的鏈接中指定的交互觸發器。 –

+0

@ RohitVats,謝謝,我沒有成功嘗試過,能否請您提供這個特定事件的例子? –

回答

0

下面是與事件觸發器在XAML定義你的榜樣。 PreviewMouseDownCommand和SelectionChangedCommand是需要在視圖模型中聲明的RelayCommands。

<TextBox x:Name="Job" 
      AcceptsReturn="True" 
      AllowDrop="True" 
      HorizontalAlignment="Left"> 
      <i:Interaction.Triggers> 
       <i:EventTrigger EventName="PreviewMouseDown" > 
        <i:InvokeCommandAction Command="{Binding PreviewMouseDownCommand}" /> 
       </i:EventTrigger> 
       <i:EventTrigger EventName="SelectionChanged" > 
        <i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" /> 
       </i:EventTrigger> 
      </i:Interaction.Triggers> 
</TextBox> 

您將需要對System.Windows.Interactivity的引用才能使用事件觸發器。將其添加到窗口中的命名空間聲明中:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
相關問題