首页 > 解决方案 > 在带有 Powershell 的 WPF 中的 TextBlock 中使用变量

问题描述

我想在 WPF 的文本块中使用 powershell 变量。我怎样才能做到这一点?

Add-Type -AssemblyName PresentationFramework

$RegWUAURebootReq = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\" | Select -ExpandProperty Name | Split-Path -Leaf
$WUAURebootReq = $RegWUAURebootReq -contains "RebootRequired"

$today = Get-Date
$lastupdateinstalleddate = Get-WmiObject -Class "win32_quickfixengineering" | Select -ExpandProperty InstalledOn | Sort-Object -Descending | select -First 1
$elapsedtime = New-TimeSpan -Start $lastupdateinstalleddate -End $today | Select TotalDays | Select -ExpandProperty TotalDays
if($WUAURebootReq -or ($elapsedtime -le 3))
{
[xml]$Form =  @' 
<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    Title="Pending Restart" Height="234.574" Width="530.319" Background="#E3EDF1" WindowStartupLocation="CenterScreen">
<Grid>
    <Button Name="Restart" Content="Restart now" HorizontalAlignment="Left" Margin="263,150,0,0" VerticalAlignment="Top" Width="100" Background="#000000" Foreground="#FFFFFF"/>
    <Button Name="Postpone" Content="Remind me later" HorizontalAlignment="Left" Margin="382,150,0,0" VerticalAlignment="Top" Width="100" Background="#000000" Foreground="#FFFFFF"/>
    <TextBlock HorizontalAlignment="Left" Margin="28,30,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="106" Width="463">
    <Run FontWeight="Bold" Text="Pending Restart!"/><LineBreak/><Run Text="Last update on this computer was installed on $lastupdateinstalleddate."/>
    <LineBreak/><Run/><LineBreak/><Run Text="It's detected that restart is still pending on this computer."/><LineBreak/>
    <Run Text="Kindly restart this computer as soon as possible to make your computer compliant with the updates."/></TextBlock>
</Grid>
</Window>
'@

$NR = (New-Object System.Xml.XmlNodeReader $Form)
$Win = [Windows.Markup.XamlReader]::Load( $NR )

$Restart = $win.FindName("Restart")
$Postpone = $win.FindName("Postpone")

$Restart.Add_Click({
    #Some code
})

$Postpone.Add_Click({
    Exit
})

$Win.WindowStyle = "SingleBorderWindow"
$Win.ShowDialog()
}
else
{
    Exit
}

我无法在 TextBlock 中使用 $lastupdateinstalleddate。谢谢大家的建议。我现在已经发布了完整的代码。

我仍然发现在这里使用变量很困难。

标签: wpfpowershell

解决方案


使用 isesteroids WPF 文本框示例中的一个非常简单的示例:

  1. 将要使用的变量放在您的 xaml 代码之前。
  2. 确保您的多行文本被双引号括起来以扩展任何变量,例如。@""@

如果您在代码编辑器中查看此内容,您想要查看的行是: 第 4 行 - 您的变量 第 33 行 - 将变量定义为文本块的文本

#region XAML window definition
# Right-click XAML and choose WPF/Edit... to edit WPF Design
# in your favorite WPF editing tool
$adminname = "Guyver1"

$xaml = @"
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="300"
    ResizeMode="NoResize"
    SizeToContent="Height"
    Title="New Mail"
    Topmost="True">
    <Grid Margin="10,10,10,10" ShowGridLines="False">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock
            Grid.Column="0"
            Grid.ColumnSpan="2"
            Grid.Row="0"
            Margin="5">Please enter your details:

        </TextBlock>
        <TextBlock Grid.Column="0" Grid.Row="1" Margin="5">$adminname

        </TextBlock>
        <TextBlock Grid.Column="0" Grid.Row="2" Margin="5">Email

        </TextBlock>
        <TextBox
            Name="TxtName"
            Grid.Column="1"
            Grid.Row="1"
            Margin="5">
        </TextBox>
        <TextBox
            Name="TxtEmail"
            Grid.Column="1"
            Grid.Row="2"
            Margin="5">
        </TextBox>
        <StackPanel
            Grid.ColumnSpan="2"
            Grid.Row="3"
            HorizontalAlignment="Right"
            Margin="0,10,0,0"
            VerticalAlignment="Bottom"
            Orientation="Horizontal">
            <Button
                Name="ButOk"
                Height="22"
                MinWidth="80"
                Margin="5">OK

            </Button>
            <Button
                Name="ButCancel"
                Height="22"
                MinWidth="80"
                Margin="5">Cancel

            </Button>
        </StackPanel>
    </Grid>
</Window>
"@
#endregion

#region Code Behind
function Convert-XAMLtoWindow
{
    param
    (
        [Parameter(Mandatory=$true)]
        [string]
        $XAML
    )

    Add-Type -AssemblyName PresentationFramework

    $reader = [XML.XMLReader]::Create([IO.StringReader]$XAML)
    $result = [Windows.Markup.XAMLReader]::Load($reader)
    $reader.Close()
    $reader = [XML.XMLReader]::Create([IO.StringReader]$XAML)
    while ($reader.Read())
    {
        $name=$reader.GetAttribute('Name')
        if (!$name) { $name=$reader.GetAttribute('x:Name') }
        if($name)
        {$result | Add-Member NoteProperty -Name $name -Value $result.FindName($name) -Force}
    }
    $reader.Close()
    $result
}

function Show-WPFWindow
{
    param
    (
        [Parameter(Mandatory=$true)]
        [Windows.Window]
        $Window
    )

    $result = $null
    $null = $window.Dispatcher.InvokeAsync{
        $result = $window.ShowDialog()
        Set-Variable -Name result -Value $result -Scope 1
    }.Wait()
    $result
}
#endregion Code Behind

#region Convert XAML to Window
$window = Convert-XAMLtoWindow -XAML $xaml
#endregion

#region Define Event Handlers
# Right-Click XAML Text and choose WPF/Attach Events to
# add more handlers
$window.ButCancel.add_Click(
    {
        $window.DialogResult = $false
    }
)

$window.ButOk.add_Click(
    {
        $window.DialogResult = $true
    }
)
#endregion Event Handlers

#region Manipulate Window Content
$window.TxtName.Text = $env:username
$window.TxtEmail.Text = 'test@test.com'
$null = $window.TxtName.Focus()
#endregion

# Show Window
$result = Show-WPFWindow -Window $window

#region Process results
if ($result -eq $true)
{
    [PSCustomObject]@{
        EmployeeName = $window.TxtName.Text
        EmployeeMail = $window.TxtEmail.Text
    }
}
else
{
    Write-Warning 'User aborted dialog.'
}
#endregion Process results

例子


推荐阅读