user5349170
user5349170

Reputation: 163

WPF Datepicker event handler for PowerShell

I am trying to add an event handler to a date picker WPF control in PowerShell to trigger an event when the user selects a date. I tried following but it didn't work. Does anyone know what is the correct event handler for date picker to use in PowerShell?

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

The code snippet is below:

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

Upvotes: 0

Views: 1898

Answers (1)

Manu
Manu

Reputation: 1742

This is the Powershell/WPF code to perform the action you're asking (tested and validated) :

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

When using SelectedDateChanged, you update the text of the textbox every time you pick a date :

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

Upvotes: 1

Related Questions