2017-07-24 109 views
0

我有這種問題。 我通常通過左鍵或右鍵點擊選擇datagrid中的行。 但我需要在右鍵單擊運行命令。 我使用此代碼C#MVVM選擇行並運行命令

<DataGrid.InputBindings> <MouseBinding Command="{Binding ShowDWClickOnRightButton}" MouseAction="RightClick" CommandParameter="{Binding ElementName=myDataGrid, Path=SelectedItem}"/> </DataGrid.InputBindings>

但這不工作,因爲在命令參數我有空(無選擇項)。你能給我一些建議如何解決這個問題嗎?

謝謝

+0

我寫了一個行爲,選擇項上單擊鼠標右鍵。這是一個TreeView,但我認爲你可以調整它爲一個GridView。看看:https://stackoverflow.com/a/43118460/7713750 – Rekshino

+0

我試着檢查你的解決方案...我需要選擇和運行命令選定的行。所以希望這是可能的。 – MarekJ

回答

0

不能使用SelectedItem因爲單擊鼠標右鍵時沒有設置。

  1. 您可以設置selectedItem before right mouse button is pressed

  2. 調用一些方法從您的視圖模型直接從代碼隱藏有相應的行對象: WPF:

    < DataGrid Grid.Row="1" x:Name="myDataGrid" MouseRightButtonDown="myDataGrid_MouseRightButtonDown" ...

代碼隱藏:

private void myDataGrid_MouseRightButtonDown(object sender, MouseButtonEventArgs e) 
     { 
      if (e.OriginalSource == null) return; 
      var row = ItemsControl.ContainerFromElement((DataGrid)sender, e.OriginalSource as DependencyObject) as DataGridRow; 

      if (row != null) 
      { 
       (this.DataContext as ViewModel).SomeViewModelMethod(row.DataContext as YourRowClass); 
      } 
     } 
  • 設置命令在ItemTemplate想在這個answer
  • +0

    我嘗試檢查,但是在沒有代碼的情況下尋找解決方案。 – MarekJ