将事件绑定到使用 WPF 中的数据模板创建的控件

Aag*_*nor 2 c# wpf datatemplate event-handling

在我的 WPF 项目中,我在代码隐藏中创建了一个自定义 ListView。在这个 ListView 中有一列包含一个按钮,由我的资源字典中的数据模板定义。

<DataTemplate x:Key="DataTemplate_EditButton">
  <Button Style="{DynamicResource Button_Image}" Width="25" ... />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

当我初始化 ListView 时,我使用以下代码创建列:

GridViewColumn buttonColumn = new GridViewColumn();
DataTemplate dt = Application.Current.TryFindResource("DataTemplate_EditButton") as DataTemplate;
buttonColumn.CellTemplate = dt;
...

gridView.Columns.Add(buttonColumn);
Run Code Online (Sandbox Code Playgroud)

现在我想将一个事件处理程序绑定到按钮的点击事件。我不能在模板中执行此操作,因为我需要为 Dictionary 创建一个隐藏类的代码,并且无论如何我都需要 ListView-UserControl 中的事件处理程序。当我使用数据模板创建列时,当然无法访问为每一行创建的按钮。

处理以所述方式创建的按钮的点击事件的最佳方法是什么?

提前致谢,
弗兰克

Evk*_*Evk 5

由于您的模板在许多控件之间共享 - 好方法可能是使用路由命令。首先声明一个命令(或使用现有命令之一,例如来自ApplicationCommands类):

public static class Commands {
    public static RoutedCommand EditRow = new RoutedCommand("Edit", typeof(Commands));
}
Run Code Online (Sandbox Code Playgroud)

在您的模板中使用此命令:

<DataTemplate x:Key="DataTemplate_EditButton">
    <Button x:Name="button" Command="{x:Static my:Commands.EditRow}" />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

然后绑定到您的控件中的该命令(在构造函数中):

this.CommandBindings.Add(new CommandBinding(Commands.EditRow, EditButtonClicked));

private void EditButtonClicked(object sender, ExecutedRoutedEventArgs args) 
{
    var button = args.OriginalSource;
    // do what you need here
}
Run Code Online (Sandbox Code Playgroud)