题
我有一个 ListBox,它具有为 ListBoxItems 定义的样式。在这个样式中,我有一些标签和一个按钮。对于该按钮,我想定义一个可以在我的页面(或使用该样式的任何页面)上处理的单击事件。如何在 WPF 页面上创建事件处理程序来处理 ListBoxItems 样式的事件?
这是我的风格(仅受影响的代码):
<Style x:Key="UsersTimeOffList" TargetType="{x:Type ListBoxItem}">
...
<Grid>
<Button x:Name="btnRemove" Content="Remove" Margin="0,10,40,0" Click="btnRemove_Click" />
</Grid>
</Style>
谢谢!
解决方案
看一眼 路由命令s。
在 myclass 中的某处定义您的命令,如下所示:
public static readonly RoutedCommand Login = new RoutedCommand();
现在使用以下命令定义您的按钮:
<Button Command="{x:Static myclass.Login}" />
您可以使用 CommandParameter 获取额外信息。
现在最后但并非最不重要的一点是,开始听你的命令:
在您希望做一些好事情的类的构造函数中,您可以放置:
CommandBindings.Add(new CommandBinding(myclass.Login, ExecuteLogin));
或者在 XAML 中:
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static myclass.Login}" Executed="ExecuteLogin" />
</UserControl.CommandBindings>
然后您实现 CommandBinding 所需的委托:
private void ExecuteLogin(object sender, ExecutedRoutedEventArgs e)
{
//Your code goes here... e has your parameter!
}
您可以开始在可视化树中的任何位置监听此命令!
希望这可以帮助
PS 您还可以使用 CanExecute 委托定义 CommandBinding,如果 CanExecute 这么说,它甚至会禁用您的命令:)
PPS 这是另一个例子: WPF 中的路由命令
其他提示
正如 Arcturus 所发布的,RoatedCommands 是实现这一目标的好方法。但是,如果您的 DataTemplate 中只有一个按钮,那么这可能会更简单一些:
实际上,您可以从主机 ListBox 处理任何按钮的 Click 事件,如下所示:
<ListBox Button.Click="removeButtonClick" ... />
单击列表框中包含的任何按钮都会触发该事件。在事件处理程序中,您可以使用 e.OriginalSource 获取对所单击按钮的引用。
显然,如果您的 ListBoxItems 有多个按钮,这就太简单了,但在许多情况下它工作得很好。
您可以创建一个用户控件 (.ascx) 来容纳列表框。然后为页面添加公共事件。
Public Event btnRemove()
然后在用户控件中的按钮单击事件上
RaiseEvent btnRemove()
您还可以像任何其他方法一样通过事件传递对象。这将允许您的用户控件告诉您的页面要删除哪些内容。