Добавить событие Click в DataTable (powershell) - PullRequest
1 голос
/ 14 января 2020

Итак, у меня есть кнопка, которая вызывает эту функцию для поиска всех файлов Install.Log на компьютере. После загрузки результатов я хочу иметь событие двойного щелчка в строке, где он откроет файл журнала.

Мне трудно добавить событие щелчка, и в любое время я пытаюсь найти что-то связанные с Datatables, я нахожу материал о java. Любое руководство или ссылки будут оценены.

Спасибо в Advace

Проверьте код для себя, запустив это в PS ISE

$ComputerName = "your computer name here"
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = @'
<Window Name="Form"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="Install Logs" Height="488.773" Width="797.65" Icon = "\\bconac01\ds-support\GS_IT\Tools\Test Tools (Alx)\Tool\icon.ico" ShowInTaskbar="False"> 
    <Grid Margin="0,0,-8,-21">
        <DataGrid Name="DataGrid1" HorizontalAlignment="Left" Height="368" VerticalAlignment="Top" Width="772" Margin="10,41,0,0"/>
        <Label Content="Filter" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
        <TextBox Name="FilterTextBox" HorizontalAlignment="Left" Height="26" Margin="78,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="172"/>
    </Grid>
</Window>
'@

#Read XAML
$reader=(New-Object System.Xml.XmlNodeReader $xaml) 
try{$Software=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Some possible causes for this problem include: .NET Framework is missing PowerShell must be launched with PowerShell -sta, invalid XAML code was encountered."; exit}

# Store Form Objects In PowerShell
$xaml.SelectNodes("//*[@Name]") | ForEach-Object{
    Set-Variable -Name ($_.Name) -Value $Software.FindName($_.Name)
    Write-host $_.Name
}

$Fields = @(
    'Name'
    'LastWriteTime'
)



#$Services = Get-WmiObject -Computer ($prebox.text + $device.text) -Class Win32reg_AddRemovePrograms | Select-object -Property *
$Services = Get-ChildItem \\$ComputerName\c$\build\logs -Include *install* -recurse -ErrorAction Stop | Sort-Object LastWriteTime -Descending


# Add Services to a datatable
$Datatable = New-Object System.Data.DataTable
[void]$Datatable.Columns.AddRange($Fields)
foreach ($Service in $Services)
{
    $Array = @()
    Foreach ($Field in $Fields)
    {
        $array += $Service.$Field
    }
    [void]$Datatable.Rows.Add($array)
}
#$filter = "DisplayName LIKE 'B%'"
#$Datatable.DefaultView.RowFilter = $filter



# Create a datagrid object and populate with datatable
$DataGrid1.ItemsSource = $Datatable.DefaultView
$DataGrid1.CanUserAddRows = $False
$DataGrid1.IsReadOnly = $True
$DataGrid1.GridLinesVisibility = "None"
$DataGrid1.Add_CellMouseClick({gridClick})

function gridClick(){
$rowIndex = $DataGrid1.CurrentRow.Index
$columnIndex = $DataGrid1.CurrentCell.ColumnIndex
Write-Host $rowIndex
Write-Host $columnIndex 
Write-Host $DataGrid1.Rows[$rowIndex].Cells[0].value
Write-Host $DataGrid1.Rows[$rowIndex].Cells[$columnIndex].value}

$FilterTextBox.Add_TextChanged({
    $InputText = $FilterTextBox.Text
    $filter = "Name LIKE '$InputText%'"
    $Datatable.DefaultView.RowFilter = $filter
    $DataGrid1.ItemsSource = $Datatable.DefaultView
    $form.Controls.Add($DataGrid1)
$Software.Controls.Add($DataGrid1)
})

# Shows the form
$statusBar1.Text = "Done."

$Software.Add_Shown({$Software.Activate()})
$Software.ShowDialog() | out-null

- Вещи, которые я пробовал, которые предлагаются.

[what I see[2]

update

Ответы [ 2 ]

1 голос
/ 17 января 2020

В соответствии с вашими требованиями, вот еще один пример, который я создал с WPF с PowerShell. Вы можете привязать событие, используя $WPFListView.Add_MouseDoubleClick({gridClick}), и получить доступ к выбранному значению ячейки, используя столбец, такой как $WPFListView.SelectedValue.OriginalFileName

. Попробуйте это как в PowerShell ISE. Вот как это выглядит

##Sample DataTable 

$tabName = "SampleTable"

#Create Table object
$table = New-Object system.Data.DataTable “$tabName”

#Define Columns
$col1 = New-Object system.Data.DataColumn OriginalFileName,([string])
$col2 = New-Object system.Data.DataColumn FileDescription,([string])
$col3 = New-Object system.Data.DataColumn FileVersionRaw,([string])

#Add the Columns
$table.columns.add($col1)
$table.columns.add($col2)
$table.columns.add($col3)

#Create a row
$row = $table.NewRow()
$row.OriginalFileName = "Test Log"
$row.FileDescription = "Test log data"
$row.FileVersionRaw = "v1.0"

$row1 = $table.NewRow()
$row1.OriginalFileName = "IIS Log"
$row1.FileDescription = "IIS Sys log"
$row1.FileVersionRaw = "v2.0"

$row2 = $table.NewRow()
$row2.OriginalFileName = "User Data"
$row2.FileDescription = "User data details"
$row2.FileVersionRaw = "v1.0"

$row3 = $table.NewRow()
$row3.OriginalFileName = "Sys Info"
$row3.FileDescription = "System Info Details"
$row3.FileVersionRaw = "v2.0"

#Add the row to the table
$table.Rows.Add($row)
$table.Rows.Add($row1)
$table.Rows.Add($row2)
$table.Rows.Add($row3)

##Sample DataTable 

$inputXML = @"
<Window x:Class="FileVersionChecker.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FileVersionChecker"
        mc:Ignorable="d"
        Title="FileVersionChecker" Height="350" Width="525">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="115*"/>
                <ColumnDefinition Width="373*"/>
                <ColumnDefinition Width="29*"/>
            </Grid.ColumnDefinitions>
        <ListView Name="ListView" Grid.Column="1" HorizontalAlignment="Left" Height="150" Margin="10,10,0,0" VerticalAlignment="Top" Width="350">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="OriginalFileName" DisplayMemberBinding ="{Binding 'OriginalFileName'}" Width="100"/>
                    <GridViewColumn Header="FileDescription" DisplayMemberBinding ="{Binding 'FileDescription'}" Width="100"/>
                    <GridViewColumn Header="FileVersionRaw" DisplayMemberBinding ="{Binding 'FileVersionRaw'}" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>

    </Grid>
</Window>
"@       

$inputXML = $inputXML -replace 'mc:Ignorable="d"', '' -replace "x:N", 'N' -replace '^<Win.*', '<Window'

[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = $inputXML
#Read XAML

$reader = (New-Object System.Xml.XmlNodeReader $xaml)
try {
    $Form = [Windows.Markup.XamlReader]::Load( $reader )
}
catch {
    Write-Output "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed."
}
 $xaml.SelectNodes("//*[@Name]") | ForEach-Object {Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)}


$WPFListView.ItemsSource  = $table.DefaultView
$WPFListView.Add_MouseDoubleClick({gridClick})

function gridClick()
{
  Write-Host ""  
  Write-Host "$($WPFListView.SelectedValue.OriginalFileName) ,  $($WPFListView.SelectedValue.FileDescription), $($WPFListView.SelectedValue.FileVersionRaw)"
}


$Form.ShowDialog() | out-null;
1 голос
/ 15 января 2020

Хорошо. Вот пример с событием щелчка ячейки gridview. Вы можете добавить событие двойного щелчка ячейки с $DataGrid1.Add_CellMouseClick({gridClick})

надеюсь, это поможет

$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(900,600)
$DataGrid1 = New-Object System.Windows.Forms.DataGridView
$DataGrid1.Size=New-Object System.Drawing.Size(800,400)

$DataGrid1.Add_CellMouseClick({gridClick})

$form.Controls.Add($DataGrid1)


#Create an unbound DataGridView by declaring a column count.
$DataGrid1.ColumnCount = 4
$DataGrid1.ColumnHeadersVisible = $true

#Set the column header names.
$DataGrid1.Columns[0].Name = "Recipe"
$DataGrid1.Columns[1].Name = "Category"
$DataGrid1.Columns[2].Name = "Third COlumn"
$DataGrid1.Columns[3].Name = "Rating"

#Populate the rows.
$row1 = @("Meatloaf","Main Dish", "boringMeatloaf", "boringMeatloafRanking")
$row2 = @("Key Lime Pie","Dessert", "lime juice evaporated milk", "****")
$row3 = @("Orange-Salsa Pork Chops","Main Dish", "pork chops, salsa, orange juice", "****")
$row4 = @("Black Bean and Rice Salad","Salad", "black beans, brown rice", "****")
$row5 = @("Chocolate Cheesecake","Dessert", "cream cheese", "***")
$row6 = @("Black Bean Dip", "Appetizer","black beans, sour cream", "***")
$rows = @( $row1, $row2, $row3, $row4, $row5, $row6 )

foreach ($row in $rows){
    $DataGrid1.Rows.Add($row)
}


function gridClick(){
$rowIndex = $DataGrid1.CurrentRow.Index
$columnIndex = $DataGrid1.CurrentCell.ColumnIndex
Write-Host $rowIndex
Write-Host $columnIndex 
Write-Host $DataGrid1.Rows[$rowIndex].Cells[0].value
Write-Host $DataGrid1.Rows[$rowIndex].Cells[$columnIndex].value}


$form.ShowDialog()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...