【问题标题】:Access UserControl elements/properties from main window in a WPF XAML PowerShell script从 WPF XAML PowerShell 脚本中的主窗口访问 UserControl 元素/属性
【发布时间】: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


【解决方案1】:

你必须在$MainWindowContent中做一个FindName

$TextBox1 = $MainWindow.Content.FindName("TextBox1")

【讨论】:

  • 哦,我明白了,但是通常当我需要访问窗口的某个元素时,$MainWindow.FindName("TextBox1") 就足够了,你认为前面的$MainWindow.Content = $Page1 是需要使用的根本原因吗$MainWindow.Content.FindName("TextBox1")?如果是这样,也许有一种更简洁的方法可以将 UserControl 添加到我的窗口?
  • $MainWindow 是一个System.Windows.Controls.ContentControl。如果您执行FindName,它将仅在该控件内搜索。 $MainWindow.Content 是另一个不同的System.Windows.Controls.ContentControl。所以这就是它不起作用的原因。 WPF 有点生疏,所以不知道有什么更干净的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多