c# - 将事件绑定(bind)到使用 WPF 中的数据模板创建的控件

标签 c# wpf event-handling datatemplate

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

<DataTemplate x:Key="DataTemplate_EditButton">
  <Button Style="{DynamicResource Button_Image}" Width="25" ... />
</DataTemplate>

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

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

gridView.Columns.Add(buttonColumn);

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

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

提前致谢,
弗兰克

最佳答案

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

public static class Commands {
    public static RoutedCommand EditRow = new RoutedCommand("Edit", typeof(Commands));
}

在模板中使用此命令:

<DataTemplate x:Key="DataTemplate_EditButton">
    <Button x:Name="button" Command="{x:Static my:Commands.EditRow}" />
</DataTemplate>

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

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

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

关于c# - 将事件绑定(bind)到使用 WPF 中的数据模板创建的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44760674/

相关文章:

javascript - 添加到表单数据的 JavaScript 对象在服务器上始终接收为 null

c# - 我如何跟踪对数据库表的任何更改

c# - Active TabPage 与我的控件颜色相同

wpf - 单击按钮时验证 ViewModel

javascript - HTML5如何获取被点击对象的id?

javascript - DIV 使用事件处理程序更改颜色 "click"

c# - 如何不允许用户在文本框中输入数字

c# - WPF 项目中每个字典条目必须有一个关联的键错误

c# - 如何在WPF中获取图像的正确位置?

Laravel 5 - 事件处理程序和监听器之间的混淆