【问题标题】:WPF + XAML + DataGrid + Powershell 2.0WPF + XAML + 数据网格 + Powershell 2.0
【发布时间】:2015-07-13 01:28:24
【问题描述】:

我正在尝试将数据网格放入 WPF。在 Powershell 中很简单。但是当我在 Powershell 2.0 中运行代码时,它找不到给我错误。

示例代码:

Add-Type -AssemblyName PresentationFramework

$xaml = [xml] @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="My window" Height="300" Width="300">
<DockPanel>
    <Button x:Name="okButton" Content="OK" DockPanel.Dock="Bottom" />
    <DataGrid x:Name="DataGrid" DockPanel.Dock="Top"/>
</DockPanel>
</Window>
"@

$reader = New-Object System.Xml.XmlNodeReader $xaml
$form = [Windows.Markup.XamlReader]::Load($reader)

$okButton = $form.FindName("okButton")

$okButton.add_Click({ $form.Close() })

$form.WindowStartupLocation = "CenterScreen"
$form.ShowDialog();

如果删除此行,一切正常:

<DataGrid x:Name="DataGrid" DockPanel.Dock="Top"/>

有人有什么建议吗?

我在 Powershell 2.0 中遇到的错误:

使用“1”个参数调用“Load”的异常:“标签‘DataGrid’ XML 命名空间 'http://schemas.microsoft.com/winfx 中不存在 /2006/xaml/演示文稿”。行 '0' 位置 '0'。”在行:15 字符:42 + $form = [Windows.Markup.XamlReader]::Load

【问题讨论】:

  • 您收到了哪些具体错误?我想到了 2 个可能的选项:不同的 .net 版本,或需要额外的参考加载,或两者兼而有之。
  • 查看有错误的更新问题..
  • 在 PS 4.0、.NET 4.5 中运行良好。你有什么版本的 .NET?
  • 我知道它确实如此.. 问题是为什么它在 PS 2.0 中不起作用.. 我有一个只有 PS 2.0 的环境.. :/
  • 不必太激动 ;) 我想说的是,该错误似乎特定于 PowerShell 版本 2。我还可以确认 .NET 版本不适用。

标签: wpf xaml powershell datagrid


【解决方案1】:

默认情况下,PowerShell 2.0 将使用 .NET 框架 2.0。 .NET v 2.0 中没有 DataGrid。类型:

[environment]::Version

如果你得到这个,或者其他以 2 开头的东西......

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      50727  7905

您的 PowerShell 会话使用的是 NET 2.0。 How to "Enable .Net 4.0 access from PowerShell V2"?

编辑:

在 PS 2.0 上解决此问题 ....

使用以下内容创建文件 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.config 和 C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe.config:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <startup useLegacyV2RuntimeActivationPolicy="true"> 
        <supportedRuntime version="v4.0" />    
    </startup> 
</configuration>

在此之后,您可以加载 .NET 4 运行时:

Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF\PresentationFramework.dll"

假设您已加载 .NET 4。

【讨论】:

  • 很好地回答了为什么它不起作用.. 但是为什么我可以使用:New-Object System.Windows.Forms.DataGridView in System.Windows.Forms
  • System.Windows.Forms 和 PresentationFramework 是两种截然不同的动物。你的代码加载System.Windows.Controls.DataGrid
  • 我假设我无法在 Powershell 2.0 中加载 System.Windows.Controls.DataGrid .. 对吗? :'(
  • 是的,没错。要修复它,您必须拥有 .NET 4 并修复 PS 2 才能使用它。
猜你喜欢
  • 2011-08-15
  • 2021-01-27
  • 2011-02-23
  • 2010-12-06
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 2015-11-02
  • 2012-12-27
相关资源
最近更新 更多