【问题标题】:Event handler in DataTemplateDataTemplate 中的事件处理程序
【发布时间】:2009-11-25 23:13:10
【问题描述】:

我在数据模板中有 WPF 组合框(列表框中有很多组合框),我想处理输入按钮。如果它是例如,那将很容易。一个按钮 - 我会使用命令 + 相对绑定路径等。不幸的是,我不知道如何使用命令处理按键或如何从模板设置事件处理程序。 有什么建议吗?

【问题讨论】:

    标签: wpf event-handling datatemplate


    【解决方案1】:

    您可以在设置模板的样式中使用 EventSetter:

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

    【讨论】:

      【解决方案2】:

      我通过使用一个常用的事件处理程序解决了我的问题,我在其中遍历可视化树,找到相应的按钮并将其称为命令。 如果其他人有同样的问题,请发表评论,我会提供更多的实现细节。

      UPD

      这是我的解决方案:

      我在可视化树中搜索按钮,然后执行与按钮关联的命令。

      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);
                  }
              }
          }
      } 
      

      【讨论】:

        【解决方案3】:

        本文有一种方法可以将任何Event 路由到Command

        http://nerobrain.blogspot.nl/2012/01/wpf-events-to-command.html

        【讨论】:

          猜你喜欢
          • 2015-02-02
          • 2015-03-31
          • 2013-12-15
          • 1970-01-01
          • 2016-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-25
          相关资源
          最近更新 更多