2009-11-25 40 views
9

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

回答

4

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

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

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

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