XAML 尝试在PowerShell中使用WebView2创建WPF窗口时出错

iq3niunx  于 2023-08-01  发布在  Shell
关注(0)|答案(1)|浏览(130)

我尝试使用PowerShell(要求)创建一个带有WebView 2控件的WPF窗口,这样我就可以用本地XLST打开一个本地XML文件。我让它在Visual Studio中工作,作为使用此XAML的概念证明:

<Window x:Class="WepViewTutorial.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf">
<DockPanel>
    <wv2:WebView2 Name="webView"
              Source="C:\dev\webview2dev\xmlFile.xml"
/>
</DockPanel>
</Window>

字符串
这个很有效
当我使用PowerShell时,我发现了一些困难。以下是我的脚本:

Register-PackageSource -provider NuGet -name nugetRepository -location https://www.nuget.org/api/v2 -ErrorAction SilentlyContinue
install-Package -Name Microsoft.Web.WebView2 -SkipDependencies -Scope CurrentUser -ErrorAction SilentlyContinue

$webviewBase = "$(Get-Package *webview* | % source )"| Split-Path -Parent
add-type -LiteralPath "$webviewBase\lib\net45\Microsoft.Web.WebView2.Core.dll"
add-type -LiteralPath "$webviewBase\lib\net45\Microsoft.Web.WebView2.Wpf.dll"
Add-Type -assemblyName PresentationCore
Add-Type -assemblyName PresentationFramework
[xml]$xaml = @"
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
    x:Name = "Window">
<DockPanel>
    <wv2:WebView2 Name="webView"
              Source="C:\dev\webview2dev\xmlFile.xml"
/>
</DockPanel>
</Window>
"@
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$window.ShowDialog()


但这不管用。我得到一个错误:

Exception calling "Load" with "1" argument(s): "Cannot create unknown type 
'{clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf}WebView2'."
At C:\dev\webview2dev\poc.ps1:30 char:1
+ $window = [Windows.Markup.XamlReader]::Load($reader)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : XamlParseException


如果我从XAML中删除这一行:

<wv2:WebView2 Name="webView"
              Source="C:\dev\webview2dev\xmlFile.xml"
/>


我需要生成WPF窗口,所以我想我错过了一些与尝试在PowerShell中为窗口启动和运行WebView 2特别相关的东西。
我读过几篇文章,指出我需要将. dll放在脚本目录中。试过了,没有成功。我读到一些东西表明我需要设置用户数据文件夹,但到目前为止还没有成功地弄清楚如何完成这一点。无论如何,我想在这里提出这个问题以寻求指导,因为我觉得我误解了一些基本的东西,就如何使其发挥作用而言。任何见解/建议将不胜感激,谢谢。

edqdpe6u

edqdpe6u1#

这是工作脚本。我发现webview2.dll需要在脚本目录中。我从安装webview2的地方手动删除了它们。最终将在nuGet包安装后在脚本中包含. dll的文件副本:

function New-XamlGui {
    [CmdletBinding()]
    param (
        [parameter(Mandatory,ParameterSetName="String")]
        [string]
        $XamlXmlString,
        [Parameter(Mandatory,ParameterSetName="File")]
        [ValidateScript({Test-Path $_})]
        [string]
        $XamlFile
    )
    
    begin {
        if (-not ( ([System.Management.Automation.PSTypeName]'windows.markup.xamlreader').type ) ) {
            try {
                [void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
            }
            catch {
                #This looks odd but will stop execution of the rest of the script.
                $PSCmdlet.ThrowTerminatingError($_)
            }
        }
    }
    
    process {

        if ($PSCmdlet.ParameterSetName -eq "File"){
            $XamlXmlString = Get-Content -Raw $XamlFile
            if ( -not $XamlXmlString){
                $PSCmdlet.ThrowTerminatingError(
                    ( new-object System.Management.Automation.ErrorRecord -ArgumentList @(
                        [System.Management.Automation.RuntimeException]'EmptyOrMissingFile',
                        'EasyGUI.UnableToReadFileOrEmpty',
                        [System.Management.Automation.ErrorCategory]::InvalidData,
                        $XamlFile
                        )
                    )
                )
            }
        }

        # fix up xaml from VS:
        $XamlXmlString = $XamlXmlString -replace '(x:)?Class=".*?"',''
        $XamlXmlString = $XamlXmlString -replace "x:Name=","Name="
        $XamlXmlString = $XamlXmlString -replace '(mc:)?Ignorable=".*?"',''

        try {
            $InputXAML = [xml]$XamlXmlString
        } catch {
            #This looks odd but will stop execution of the rest of the script.
            $PSCmdlet.ThrowTerminatingError($_)
        }
        $XMLReader = New-Object System.Xml.XmlNodeReader $InputXAML
        try {
            $XAMLForm = [Windows.Markup.XamlReader]::Load($XMLReader)
        }
        catch {
            $exception = [System.Exception]::new('Failed to load XAML file.'+$_.Exception.tostring(),$_.Exception)
            $PSCmdlet.ThrowTerminatingError(
                ( new-object System.Management.Automation.ErrorRecord -ArgumentList @(
                        $exception,
                        'EasyXAML.ReaderLoadError',
                        [System.Management.Automation.ErrorCategory]::InvalidResult,
                        $InputXAML
                    )
                )
            )
        }
        

        $NamedControls = @{}
        foreach ($node in ($InputXAML.SelectNodes("//*[@Name]") ) ) {
            $NamedControls[$node.name] = $XAMLForm.FindName($node.name)
        }

        [pscustomobject]@{
            Form          = $XAMLForm
            NamedControls = $NamedControls
        }

    }
    
    end {
    $stop
    }
}

if($(Get-Package | ?{$_.Name -Eq 'Microsoft.Web.WebView2'})-eq $null){
    if(Get-PackageSource | ?{$_.Name -eq 'nuGet.org'} -eq $null){
        Register-PackageSource -provider NuGet -name nugetRepository -location https://www.nuget.org/api/v2 #-ErrorAction SilentlyContinue
    }
    install-Package -Name Microsoft.Web.WebView2 -Scope CurrentUser #-ErrorAction SilentlyContinue
}

Add-type -LiteralPath "C:\psScriptPath\Microsoft.Web.WebView2.Core.dll"
Add-type -LiteralPath "c:\psScriptPath\Microsoft.Web.WebView2.Wpf.dll"
Add-Type -assemblyName PresentationCore
Add-Type -assemblyName PresentationFramework

$inputXML = Get-content C:\psScriptPath\XAML\window.xaml -Raw
$f = New-XamlGui -XamlXmlString $inputXML
$f.form.showdialog()

字符串
对于XAML:

<Window 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
mc:Ignorable="d"
Title="DCERT Viewer" 
Height="800" Width="1200" Topmost="False" 
ResizeMode="CanResizeWithGrip" ShowInTaskbar = "True"
WindowStartupLocation = "CenterScreen"
x:Name="MainForm"
Background="AliceBlue" UseLayoutRounding="True"
>
    <Grid Background="#FFE5E5E5">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <wv2:WebView2 x:Name="_webView2" Grid.Row="1" Visibility="Visible" Source="C:\psScriptpath\xmlFile.xml" >
                    <wv2:WebView2.CreationProperties>
                <wv2:CoreWebView2CreationProperties AdditionalBrowserArguments="--allow-file-access-from-files" UserDataFolder="C:\Temp\Data"/>
            </wv2:WebView2.CreationProperties>
        </wv2:WebView2>

    </Grid>
</Window>

相关问题