【问题标题】:Using variable in TextBlock in WPF with Powershell在带有 Powershell 的 WPF 中的 TextBlock 中使用变量
【发布时间】:2019-01-21 17:55:17
【问题描述】:

我想在 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。 谢谢大家的建议。我现在已经发布了完整的代码。

我仍然觉得在这里使用变量很困难。

【问题讨论】:

  • 到目前为止您尝试过什么?您可以编辑您的问题以向我们展示。
  • @mudit 你能提供完整的powershell代码或小样本吗?谢谢
  • 您能否显示更多代码。这是另一个变量中的 XAML 吗?你把这个 XAML 放在哪里
  • 您需要保存 xaml 并应用阅读器来创建可供 powershell 使用的对象。然后您就可以使用 powershell 变量修改对象的属性。

标签: wpf powershell


【解决方案1】:

使用 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

【讨论】:

  • 非常感谢里昂。我只需要用 @".."@ 替换 @'..'@ 就可以了。
猜你喜欢
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 2020-09-08
  • 2010-09-23
相关资源
最近更新 更多