Dot-Net

將上下文菜單命令參數綁定到數據網格屬性

  • February 3, 2017

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

<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>

菜單項命令的操作在 ViewModel 中具有以下簽名:

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

現在我的問題是,SelectedItemsAction當我點擊上下文菜單項時,我到達了parameter,但是null. 我相信我的問題出在CommandParameter屬性的設置器中。如您所見,我想將此屬性綁定到SelectedItemsDataGrid 的屬性,方法是將值設置為:

<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什麼?有可能嗎?

提前感謝您的幫助!

您是否嘗試過進行祖先綁定?就像是:

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

不在 Visual Tree的ContextMenu同一部分,因此您不能使用 ElementName 等來引用DataGrid. 你將不得不使用PlacementTargetContextMenu。像這樣試試

<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>

引用自:https://stackoverflow.com/questions/4799824