2014-12-21 29 views
1

我有一個工作的MouseLeftButtonUp結合,我從View.cs工作,但我不能讓從Viewmodel.cs如何重寫這個DataGrid MouseLeftButtonUp綁定到MVVM?

XAML工作:

<DataGrid x:Name="PersonDataGrid" AutoGenerateColumns="False" 
    SelectionMode="Single" SelectionUnit ="FullRow" ItemsSource="{Binding Person}" 
    SelectedItem="{Binding SelectedPerson}" 
    MouseLeftButtonUp="{Binding PersonDataGrid_CellClicked}" > 

View.cs:

private void PersonDataGrid_CellClicked(object sender, MouseButtonEventArgs e) 
    { 
     if (SelectedPerson == null) 
      return; 

     this.NavigationService.Navigate(new PersonProfile(SelectedPerson)); 
    } 

PersonDataGrid_CellClicked方法不能從ViewModel.cs工作。我試過閱讀Blend System.Windows.Interactivity的相關內容,但還沒有嘗試過,因爲我仍然在學MVVM。

我試過DependencyProperty並嘗試了RelativeSource綁定,但無法獲取PersonDataGrid_CellClicked導航到PersonProfile UserControl。

回答

2

通過使用Blend System.Windows.Interactivity程序集,您不違反任何MVVM原則,只要沒有在VM中定義的命令內部使用與視圖直接相關的邏輯,此處如何使用它的MouseLeftButtonUp事件:

<DataGrid> 
     <i:Interaction.Triggers> 
      <i:EventTrigger EventName="MouseLeftButtonUp" > 
       <i:InvokeCommandAction 
         Command="{Binding MouseLeftButtonUpCommand}" /> 
      </i:EventTrigger> 
     </i:Interaction.Triggers> 
    </DataGrid> 

,並在視圖模型定義MouseLeftButtonUpCommand:

private RelayCommand _mouseLeftButtonUpCommand; 
    public RelayCommand MouseLeftButtonUpCommand 
    { 
     get 
     { 
      return _mouseLeftButtonUpCommand 
       ?? (_mouseLeftButtonUpCommand = new RelayCommand(
       () => 
       { 
        // the handler goes here 
       })); 
     } 
    } 
+0

感謝。鼠標按鈕現在觸發處理程序邏輯。現在我有了另一個問題,因爲我切換到UserControl而不是Page,並且我沒有意識到這會中斷NavigationService的使用。 –