2011-01-25 114 views
13

在我的XAML文件中,我有一個帶上下文菜單的DataGrid。數據源是ViewModel,它具有屬性EntityCollection(一個ObservableCollection)作爲DataGrid的ItemsSource,另一個集合ContextMenu.MenuItems作爲數據源在DataGrid上創建上下文菜單。該集合的元素有我綁定到菜單項的命令屬性Command屬性:將上下文菜單命令參數綁定到datagrid屬性

<DataGrid Name="EntityDataGrid" ItemsSource="{Binding EntityCollection}" Height="450"> 
    <DataGrid.ContextMenu> 
    <ContextMenu ItemsSource="{Binding Path=ContextMenu.MenuItems}"> 
     <ContextMenu.ItemContainerStyle> 
     <Style TargetType="{x:Type MenuItem}"> 
      <Setter Property="Command" Value="{Binding Command}" /> 
      <Setter Property="CommandParameter" 
        Value="{Binding ElementName=EntityDataGrid, Path=SelectedItems}" /> 
     </Style> 
     </ContextMenu.ItemContainerStyle> 
    </ContextMenu> 
    </DataGrid.ContextMenu> 
</DataGrid> 

菜單項命令的行動已在視圖模型以下特徵:

private void SelectedItemsAction(object parameter) 
{ 
    // Do something with "parameter" 
} 

現在我的問題是,當我點擊一個上下文菜單項時,我達到SelectedItemsAction,但parameternull。我相信我的問題在於CommandParameter屬性的設置者。正如你所看到的,我想通過將該值設置爲這個屬性到DataGrid的SelectedItems屬性綁定:作爲測試

<Setter Property="CommandParameter" 
     Value="{Binding ElementName=EntityDataGrid, Path=SelectedItems}" /> 

我試過簡單值:

<Setter Property="CommandParameter" 
     Value="{Binding ElementName=EntityDataGrid, Path=Height}" /> 

這裏parameter仍然是null。然後,只是爲了測試,如果任何參數達到我的操作方法都:

<Setter Property="CommandParameter" 
     Value="10" /> 

這工作,在我的操作方法的parameter現在確實10

我在做什麼錯誤將CommandParameter的值綁定到EntityDataGrid的屬性?它有可能嗎?

感謝您提前幫忙!

回答

7

你有沒有嘗試做一個祖先綁定?喜歡的東西:

<Setter Property="CommandParameter" 
     Value="{Binding Path=SelectedItems, 
     RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" /> 
+0

很好,謝謝你,這個作品! (現在我只需要多讀一點關於WPF綁定的內容,以瞭解您的代碼的確在做什麼;)) – Slauma 2011-01-26 11:31:32

+0

它正在樹上找到與該類型匹配的項目。第一個它使用它作爲綁定上下文。 – CodeWarrior 2011-01-26 14:22:08

11

ContextMenu是不是在視覺樹的同一部分,所以這就是爲什麼你不能使用的ElementName等引用DataGrid。您必須改用ContextMenuPlacementTarget。嘗試像這樣

<ContextMenu ItemsSource="{Binding Path=ContextMenu.MenuItems}"> 
    <ContextMenu.ItemContainerStyle> 
     <Style TargetType="{x:Type MenuItem}"> 
      <Setter Property="Command" Value="{Binding Command}" /> 
      <Setter Property="CommandParameter" 
        Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, 
            Path=PlacementTarget.SelectedItems}" /> 
     </Style> 
    </ContextMenu.ItemContainerStyle> 
</ContextMenu>