【发布时间】:2015-03-06 23:47:28
【问题描述】:
我编写了以下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 对象来访问它?
【问题讨论】:
-
您的意思是您需要访问 $Page1 对象中的元素吗?不是 $MainWindow 对象?
-
我的意思是,在将
$Page1对象添加到$MainWindow.Content之后,我应该能够从$MainWindow访问TextBox1,而我当前的代码并非如此。
标签: wpf xaml powershell powershell-4.0