WPF列表框样式(带按钮)

时间:2020-03-05 18:43:19  来源:igfitidea点击:

我有一个具有为Lis​​tBoxItems定义的样式的ListBox。在这种样式内,我有一些标签和一个按钮。我想定义一个按钮,该按钮可以在我的页面(或者使用该样式的任何页面)上处理。如何在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>

谢谢!

解决方案

回答

我们可以创建一个用户控件(.ascx)来容纳列表框。然后为页面添加一个公共事件。

Public Event btnRemove()

然后在用户控件中的按钮单击事件上

RaiseEvent btnRemove()

我们还可以像其他任何方法一样通过事件传递对象。这将使用户控件告诉页面要删除的内容。

回答

看一下RoutedCommands。

在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中的RoutedCommands

回答

如Arcturus所述,RoutedCommands是实现此目标的好方法。但是,如果DataTemplate中只有一个按钮,那么这可能会更简单一些:

我们实际上可以从主机ListBox处理任何按钮的Click事件,如下所示:

<ListBox Button.Click="removeButtonClick" ... />

单击列表框中包含的任何按钮时,都会触发该事件。在事件处理程序中,我们可以使用e.OriginalSource来获得对单击按钮的引用。

显然,如果ListBoxItem具有多个按钮,这太简单了,但是在许多情况下,它都可以正常工作。