2011-09-25 34 views
0

我有一个窗口,有一些选项卡,在每个选项卡中我可以创建一个新项目。
我想定义一个短键来创建新的item.But我想我的短键在活动标签上工作。
例如,当Tab1处于活动状态时,我的快捷键在Tab1中创建项目或在Tab2处于活动状态时处理,而我的快捷键则用于在Tab2中创建项目。我如何使用活动选项卡上的一个短键?如何使用活动选项卡上的一个短键?

回答

1

有很多方法可以做到这一点。最常见的是使用命令。首先,这里我使用了XAML:

<Grid> 
    <TabControl Grid.Row="0" 
       x:Name="AppTabs"> 
     <TabItem Header="Tab 1"> 
      <ListBox x:Name="TabOneList" /> 
     </TabItem> 

     <TabItem Header="Tab 2"> 
      <ListBox x:Name="TabTwoList" /> 
     </TabItem> 
    </TabControl> 
</Grid> 

下面的代码隐藏:

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
    // create the new item command and set it to the shortcut Ctrl + N 
    var newItemCommand = new RoutedUICommand("New Item", "Makes a new item on the current tab", typeof(MainWindow)); 
    newItemCommand.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control, "Ctrl + N")); 

    // create the command binding and add it to the CommandBindings collection 
    var newItemCommandBinding = new CommandBinding(newItemCommand); 
    newItemCommandBinding.Executed += new ExecutedRoutedEventHandler(newItemCommandBinding_Executed); 
    CommandBindings.Add(newItemCommandBinding); 
} 

private void newItemCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) 
{ 
    // one way to get the ListBox control from the currently selected tab 
    ListBox itemList = null; 
    if (AppTabs.SelectedIndex == 0) 
     itemList = this.TabOneList; 
    else if (AppTabs.SelectedIndex == 1) 
     itemList = this.TabTwoList; 

    if (itemList == null) 
     return; 

    itemList.Items.Add("New Item"); 
} 

我不会考虑这种生产代码,但希望它指向你在正确的方向。

+0

坦克你mbursill.I是想知道我怎么能用这种方式在mvvm? –

相关问题