数据模板中的事件处理程序

11

我有一个WPF ComboBox,它处于数据模板中(列表框中有很多个ComboBox),我想处理回车键的操作。如果这是一个按钮那就容易了 - 我可以使用命令(Command) + 相对绑定路径(Relative binding path)等。不幸的是,我不知道如何使用Command来处理按键事件,或者如何从模板设置事件处理程序。 有什么建议吗?

4个回答

15

您可以在使用模板的同时,使用EventSetter:

<Style TargetType="{x:Type ListBoxItem}">
      <EventSetter Event="MouseWheel" Handler="GroupListBox_MouseWheel" />
      <Setter Property="Template" ... />
</Style>

4
我通过使用常规事件处理程序解决了我的问题,在其中遍历可视树,找到相应的按钮并调用其命令。如果其他人有同样的问题,请发表评论,我将提供更多实现细节。 更新: 这是我的解决方案:
我搜索可视树以查找按钮,然后执行与按钮相关联的命令。
View.xaml:
<ComboBox KeyDown="ComboBox_KeyDown"/>
<Button Command="{Binding AddResourceCommand}"/>

View.xaml.cs:

private void ComboBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        var parent = VisualTreeHelper.GetParent((DependencyObject)sender);
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);

        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i) as Button;
            if (null != child)
            {
                child.Command.Execute(null);
            }
        }
    }
} 

0

0
另一个简单的选择是像这样派生控件
  public class MyTextbox : TextBox
  {
    private void OnKeyDown(object sender, KeyEventArgs e)
    {
      e.Handled = true;
      //...
      return;
    }

    private void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
      //E.g. delete the content when focused
      e.Handled = true;
      this.Text = null;
      return;
    }

    public override void OnApplyTemplate()
    {
      base.OnApplyTemplate();
      this.GotKeyboardFocus += OnGotKeyboardFocus;
      this.KeyDown += OnKeyDown;
    }
  }

如果你只想让控件始终以这种方式运行,而不是在 OnApplyTemplate() 中添加事件,当然可以直接重写虚拟方法,例如。
    protected override void OnGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e)
    {
      e.Handled = true;
      this.Text = null;
      return;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接