在我的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
,但parameter
是null
。我相信我的問題在於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
的屬性?它有可能嗎?
感謝您提前幫忙!
很好,謝謝你,這個作品! (現在我只需要多讀一點關於WPF綁定的內容,以瞭解您的代碼的確在做什麼;)) – Slauma 2011-01-26 11:31:32
它正在樹上找到與該類型匹配的項目。第一個它使用它作爲綁定上下文。 – CodeWarrior 2011-01-26 14:22:08