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

不羁的心 提交于 2019-12-11 20:14:58

问题


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()

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>

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?


回答1:


You have to do a FindName in the Content of $MainWindow

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


来源:https://stackoverflow.com/questions/28900141/access-usercontrol-elements-properties-from-main-window-in-a-wpf-xaml-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!