我编写了以下Test.ps1
PowerShell脚本来显示WPF GUI:
function LoadXamlFile( $path )
{
[System.Xml.XmlDocument]$xml = Get-Content -Path $path
$xmlReader = New-Object -TypeName System.Xml.XmlNodeReader -ArgumentList $xml
$xaml = [System.Windows.Markup.XamlReader]::Load( $xmlReader )
return $xaml
}
# Main Window
$MainWindow = LoadXamlFile 'MainWindow.xaml'
# Page 1
$Page1 = LoadXamlFile 'Page1.xaml'
$MainWindow.Content = $Page1
$TextBox1 = $MainWindow.FindName('TextBox1')
# The following line fails because $TextBox1 is null
$TextBox1.Text = 'test'
$MainWindow.ShowDialog()
此脚本需要以下两个XAML文件:
MainWindow.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="MainWindow"
Title="WPF Test" Height="200" Width="400">
</Window>
Page1.xaml
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Page1">
<Grid>
<TextBox x:Name="TextBox1" HorizontalAlignment="Center" Height="23" Margin="0,-40,0,0" TextWrapping="Wrap" VerticalAlignment="Center" Width="120"/>
<Button x:Name="Button1" Content="Next" HorizontalAlignment="Center" Margin="0,40,0,0" VerticalAlignment="Center" Width="76"/>
</Grid>
</UserControl>
我的PowerShell代码中提到的问题是,在将UserControl添加到主窗口后,我无法访问UserControl元素/属性。
我知道我可以使用$Page1.FindName('TextBox1')
访问它,但有没有办法从$MainWindow
对象执行此操作?
答案 0 :(得分:1)
您必须FindName
Content
$MainWindow
$TextBox1 = $MainWindow.Content.FindName("TextBox1")
{{1}}