2009-11-25 87 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>