如何在PowerShell ISE中使用WPF DataGrid (.Net 4.0)?

3

我发现了一个关于在PowerShell中加载.net 4.0 dll的问题。

现在,我想知道我需要使用哪个Add-Type,才能够在PowerShell ISE中使用WPF Datagrid

在此之前,以下内容是有效的:

[xml] $xaml = @"
<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="MainWindow" Height="350" Width="525">
  <DataGrid Height="200" Width="500" HorizontalAlignment="Left" Margin="12,21,0,0"
  Name="McDataGrid" VerticalAlignment="Top" RowHeight="30" ColumnWidth="100"      >
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Form=[Windows.Markup.XamlReader]::Load( $reader )

$Form.ShowDialog() 

似乎有一些WPF工具包的示例。 - JPBlanc
为什么有人在拥有.NET 4.0的情况下还要安装WPF工具包3.5呢?它们两者略有不同。 - bernd_k
1个回答

3

这是多个错误的组合。

  1. 缺少标签结尾处的斜杠。
  2. 我在powershell_ise.exe.Config中有一个TYPO,.Net 4.0程序集没有加载。
  3. 检查已加载的程序集是个好习惯,可以使用

    [System.AppDomain]::CurrentDomain.GetAssemblies() | sort location

现在这里有一个可用的解决方案。

function Invoke-sql1
{
    param( [string]$sql,
           [System.Data.SQLClient.SQLConnection]$connection
           )
    $cmd = new-object System.Data.SQLClient.SQLCommand($sql,$connection)
    $ds = New-Object system.Data.DataSet
    $da = New-Object System.Data.SQLClient.SQLDataAdapter($cmd)
    $da.fill($ds) | Out-Null
    return $ds.tables[0].rows
}


[xml] $xaml = @"
<Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid 
            AutoGenerateColumns="True" 
            HorizontalAlignment="Left" 
            Name="dataGrid1" 
            VerticalAlignment="Top" 
            Width="330"
            HeadersVisibility="All" 
            >
            <DataGrid.Columns>
                <DataGridTextColumn Header="title"
                                Binding="{Binding title}" 
                                />
                <DataGridTextColumn Header="itemid"
                                Binding="{Binding itemid}" 
                                />
            </DataGrid.Columns>
        </DataGrid >
    </Grid>
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Form=[Windows.Markup.XamlReader]::Load( $reader )


$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = "Data Source=localhost;Initial Catalog=ABDATA;Integrated Security=True"
$con.open()

$sql = @"
SELECT 'abc' title, 3 itemid
union
SELECT 'xyz' title, 2 itemid
union
SELECT 'efg' title, 1 itemid
"@

$dg = $Form.FindName("dataGrid1")
$dg.ItemsSource = @(Invoke-sql1 $sql $con)
$Form.ShowDialog() 

唯一的主要问题是我必须自己定义列。我认为这可以自动完成。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接