2013-06-18 29 views
0

我用下面的代碼來獲得數據網格的文本菜單單擊視圖模型文本菜單點擊

代碼片段[XAML]

代碼片段[C#]

private BaseCommand exportcommand; 

    public BaseCommand ExportCommand 
    { 
     get 
     { 
      if (exportcommand == null) 
       exportcommand = new BaseCommand(ExportCommandExcecuted); 

      return exportcommand; 
     } 
    } 

    public void ExportCommandExcecuted(object param) 
    { 
     var grid = param as GridDataControl; 
    } 

但我無法獲得作爲DataGrid的Command參數。你可以請看看這個,並提供建議,以實現ViewModel中的這個dataGrid。在此先感謝

回答

0

我不知道如果我應該甚至告訴你如何做到這一點,因爲你打破了MVVM,如果你基本上這樣做,我不能找出你想要這個功能的原因。

如果你不使用MVVM,那麼你可以嘗試有在VM您MenuItem這樣

<MenuItem Command="{Binding ExportCommand}" 
      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget}" 
      Header="Export To Excel" /> 

如果你使用MVVM,

只是不引用UI元素。您在VM中獲得了ItemSource集合。提出一個簡單的簡單的ICommand並且您需要的所有數據都可用,而不需要將DataGrid接收到VM。

+0

你必須在XAML中設置'ContextMenu'的'PlacemenTarget'與數據網格本身...像'' –

+0

@ WPF it it你不用「不得不」。 OP的'ContextMenu'在xaml的''內,如果我只是在切換CommandParameter的情況下完全複製它,那麼可以很好地獲得對'DataGrid'的引用。 – Viv

+0

是的,這是正確的。我的錯。 :-) –