我想将上下文菜单与Out-GridView
窗口相关联。 Out-GridView
似乎没有本地方法来执行此操作。
以下是Out-DataGrid
功能。
以下是将文件夹项目传送到Out-DataGrid
的示例。要显示的属性将传递给Out-DataGrid
。定义了一个上下文菜单,它提供了一些操作:
ls 'C:\Windows' |
Out-DataGrid FullName, Extension, Mode, Attributes, LastWriteTime `
-context_menu_items `
@{
name = 'Explorer'
action = { param($dg) explorer $dg.SelectedItem.FullName }
},
@{
name = 'Notepad'
action = { param($dg) notepad $dg.SelectedItem.FullName }
},
@{
name = 'Run'
action = { param($dg) & $dg.SelectedItem.FullName }
}
生成的窗口和上下文菜单:
列出后台作业的另一个例子:
Get-Job | Out-DataGrid Id, Name, State, HasMoreData, Command -context_menu_items `
@{
name = 'Receive'
action = { param($dg) Receive-Job -Keep $dg.SelectedItem | Out-GridView }
},
@{
name = 'Remove'
action = { param($dg) Remove-Job $dg.SelectedItem }
}
结果窗口:
我的问题是,有更好的方法来做到这一点吗?
[void][System.Reflection.Assembly]::LoadWithPartialName('PresentationFramework')
function Out-DataGrid ($properties, $context_menu_items)
{
$data_grid = New-Object -TypeName System.Windows.Controls.DataGrid -Property @{
IsReadOnly = $true
AutoGenerateColumns = $false
}
foreach ($elt in $properties)
{
$data_grid.Columns.Add((New-Object -TypeName System.Windows.Controls.DataGridTextColumn `
-Property @{
Header = $elt
Binding = (New-Object System.Windows.Data.Binding -ArgumentList @(, $elt))
}))
}
$data_grid.ItemsSource = @($input)
if ($context_menu_items)
{
$data_grid.ContextMenu = New-Object -TypeName System.Windows.Controls.ContextMenu
foreach ($elt in $context_menu_items)
{
$menu_item = New-Object -TypeName System.Windows.Controls.MenuItem
$menu_item.Header = $elt.name
$menu_item.Add_Click({
param($sender, $event_args)
$elt.action.Invoke($data_grid)
}.GetNewClosure())
$data_grid.ContextMenu.AddChild($menu_item)
}
}
$grid = New-Object System.Windows.Controls.Grid
$grid.Children.Add($data_grid) | Out-Null
$window = New-Object System.Windows.Window -Property @{ Content = $grid }
$window.ShowDialog() | Out-Null
$data_grid.SelectedItem
}