Home > Back-end >  Powershell with XAML: Handle click event of button inside ListBox datatemplate
Powershell with XAML: Handle click event of button inside ListBox datatemplate

Time:02-10

I have created a XAML document that contains a listbox. The DataTemplate for the ListBox.ItemTemplate contains a TextBlock and a Button (ommitting irrelevant properties for brevity)

<DataTemplate>
    <TextBlock Text={Binding AppName} />
    <Button Name="btnRefresh" Content="Refresh"/>
</DataTemplate>

I am displaying and handling this XAML with Powershell. Is there a way to add a click event to the button from Powershell as the controls in the DataTemplate do not get enumerated when I read in the XAML, so I cannot simply reference the variable and append an Add_Click handler to it:

$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$window.FindName("btnRefresh").add_click({...

So on clicking the button i'd then need determine which button has been clicked if there are many rows in the ListBox. Ideally the EventArgs for the click event would pass some data pertaining to the ListBoxItem to which the button is attached.

Just re-iterating that any solutions must be for Powershell, not C#.

Thanks

CodePudding user response:

You don't need to add an event handler to the Button in the ItemTemplate. You could handle the attached ButtonBase.Click event of the ListBox itself, e.g.:

$listBox.AddHandler([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent, 
    $ClickHandler)

In the handler you could then get a reference to the clicked button using the OriginalSource property of the RoutedEventArgs.

  • Related