本文介绍了在 WPF XAML PowerShell 脚本中从主窗口访问 UserControl 元素/属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下 Test.ps1 PowerShell 脚本来显示 WPF GUI:

I wrote the following Test.ps1 PowerShell script to display a 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 文件:

This script requires the two following XAML files:

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 对象中访问它?

The issue, as stated in my PowerShell code, is that I can't access UserControl elements/properties after adding the UserControl to the main window.I know I can access it with $Page1.FindName('TextBox1') but is there a way to do it from the $MainWindow object?

推荐答案

你必须在$MainWindowContent中做一个FindName

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

这篇关于在 WPF XAML PowerShell 脚本中从主窗口访问 UserControl 元素/属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:14