我创建了一个包含列表框的XAML文档。ListBox.ItemTemplate的DataTemplate包含一个TextBlock和一个Button(为简洁起见,省略了不相关的属性(
<DataTemplate>
<TextBlock Text={Binding AppName} />
<Button Name="btnRefresh" Content="Refresh"/>
</DataTemplate>
我正在使用Powershell显示和处理此XAML。有没有一种方法可以从Powershell向按钮添加点击事件,因为当我读取XAML时,DataTemplate中的控件不会被枚举,所以我不能简单地引用变量并向其附加add_click处理程序:
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)
$window.FindName("btnRefresh").add_click({...
因此,在单击按钮时,如果ListBox中有很多行,我需要确定单击了哪个按钮。理想情况下,单击事件的EventArgs会传递一些与按钮所附ListBoxItem相关的数据。
只是重申,任何解决方案都必须针对Powershell,而不是C#。
感谢
您不需要向ItemTemplate
中的Button
添加事件处理程序。您可以处理ListBox
本身的附加ButtonBase.Click
事件,例如:
$listBox.AddHandler([System.Windows.Controls.Primitives.ButtonBase]::ClickEvent,
$ClickHandler)
然后,在处理程序中,您可以使用RoutedEventArgs
的OriginalSource
属性获得对单击按钮的引用。