【发布时间】:2021-07-03 17:06:58
【问题描述】:
大家好,我在尝试使用 XAML 文件运行脚本时遇到错误。下面的错误。我还附上了我在 Visual Studio 中制作的 WPF 表单中导致错误的代码。当我从表单中删除此代码时,脚本会很好地加载 XAML 文件。我做错了什么?
错误: 使用“1”参数调用“加载”的异常:“无法从文本“CheckBox1_Click”创建“点击”。”
在 XAML\Script.ps1:30 char:5 的路径
$window = [Windows.Markup.XamlReader]::Load($reader)
CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
FullyQualifiedErrorId : XamlParseException
#Assembly and Sharepoint Connection Code
Add-Type -AssemblyName PresentationFramework
#Gets user name of the user running the script (Only first and last initial)
$UserName = $env:username.ToCharArray() | Select -First 2
$UserInitials = $UserName -Join ""
#XAML GUI Code
$xamlFile = "Path of XAML file"
#GUI Creation Code
$inputXML = Get-Content $xamlFile -Raw
$inputXML = $inputXML -replace 'mc:Ignorable="d"', '' -replace "x:N", 'N' -replace '^<Win.*', '<Window'
[XML]$XAML = $inputXML
#Read XAML
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
try
{
$window = [Windows.Markup.XamlReader]::Load($reader)
}
catch
{
Write-Warning $_.Exception
throw
}
#Create variables based on form control names
$xaml.SelectNodes("//*[@Name]") | ForEach-Object {
#"trying item $($_.Name)";
try
{
Set-Variable -Name "var_$($_.Name)" -Value $window.FindName($_.Name) -ErrorAction Stop
}
catch
{
throw
}
}
Get-Variable var_*
#Code from the click event in my WPF form
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CheckBox1_Click(object sender, RoutedEventArgs e)
{
if (CheckBox1.IsChecked == true)
{
CheckBox2.IsEnabled = false;
CheckBox2.IsChecked = false;
CheckBox3.IsEnabled = false;
CheckBox3.IsChecked = false;
CheckBox4.IsEnabled = false;
CheckBox4.IsChecked = false;
CheckBox5.IsEnabled = false;
CheckBox5.IsChecked = false;
}
else
{
CheckBox2.IsEnabled = true;
CheckBox3.IsEnabled = true;
CheckBox4.IsEnabled = true;
CheckBox5.IsEnabled = true;
}
}
}
【问题讨论】:
-
显然 PresentationFramework 在 GetTypes 方法执行之前不可用,因此我们必须添加
-PassThru像这样:Add-Type -AssemblyName PresentationFramework -PassThru | Out-Null。当您键入TAB以完成命令时,也会发生这种情况。见discussion。
标签: c# wpf powershell xaml