【问题标题】:WPF Datepicker event handler for PowerShellPowerShell 的 WPF Datepicker 事件处理程序
【发布时间】:2018-03-29 07:04:53
【问题描述】:

我正在尝试将事件处理程序添加到 PowerShell 中的日期选择器 WPF control 以在用户选择日期时触发事件。我尝试了以下但没有奏效。有谁知道日期选择器在 PowerShell 中使用的正确事件处理程序是什么?

$dpDate.Add_SelectedDateChanged({ do-something-here })

代码sn-p如下:

<DatePicker x:Name="dpDate" HorizontalAlignment="Left" VerticalAlignment="Top" Width="105" Focusable="false"/>

$dpDate.Add_SelectedDateChanged
    ({ 
        $DateFormat = get-date $dpDate.SelectedDate -f yyy-MM-dd
        $tb_FinalDate.text = $DateFormat
    })

【问题讨论】:

  • 您要调用什么样的操作?这是一个示例:$dpDate.Add_SelectedDateChanged({ Write-Host "You have selected : " $dpDate.Text })。每次选择日期时,新日期都会显示在 Powershell 控制台中
  • 谢谢,马努。当挑选日期时,我要执行的操作是,使用所选日期更新另一个文本框。我尝试通过从处理程序调用非常简单的操作,但没有被触发,所以想知道“Add_SelectedDateChanged”是否为 datapicker 正确的事件处理程序。
  • 你能提供你试过的代码吗?通常这很容易,因为您有正确的处理程序来执行此操作。例如:$dpDate.Add_SelectedDateChanged({ $textbox.Text = $dpDate.Text }) 将使用选择的日期更新您的文本框。
  • 我在上面的帖子里放了代码sn-p。

标签: wpf powershell datepicker


【解决方案1】:

这是执行您要求的操作的 Powershell/WPF 代码(经过测试和验证):

Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
[xml]$xaml=@"
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Test"
        Title="MainWindow" Height="265" Width="371">
    <Grid>
        <DatePicker x:Name="dpDate" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="tb_FinalDate" HorizontalAlignment="Left" Height="23" Margin="10,55,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="149"/>

    </Grid>
</Window>

"@

$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load($reader)

#Turn XAML into PowerShell objects
$xaml.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'x:Name')]]") | ForEach-Object{
    Set-Variable -Name ($_.Name) -Value $Window.FindName($_.Name)
}

$dpDate.Add_SelectedDateChanged({
    $tb_FinalDate.Text = Get-Date($dpDate.Text) -Format 'yyyy-MM-dd'
})

#Display Form
$Window.ShowDialog() | Out-Null

使用SelectedDateChanged 时,每次选择日期时都会更新文本框的文本:

$dpDate.Add_SelectedDateChanged({
    $tb_FinalDate.Text = Get-Date($dpDate.Text) -Format 'yyyy-MM-dd'
})

【讨论】:

  • Manu,借助您的工作示例,我能够识别并修复我的代码。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 2011-01-15
  • 2017-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多