我想将上下文菜单与一个
以下是一个
下面是一个示例,其中文件夹项目被传递到
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
}