在 WPF XAML PowerShell 脚本中从 main window 访问 UserControl elements/properties

Access UserControl elements/properties from main window in a WPF XAML PowerShell script

我编写了以下 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 添加到主 window 后我无法访问 UserControl elements/properties。 我知道我可以使用 $Page1.FindName('TextBox1') 访问它,但是有没有办法从 $MainWindow 对象访问它?

您必须在 $MainWindow

Content 中执行 FindName
$TextBox1 = $MainWindow.Content.FindName("TextBox1")