2011-01-14 87 views

回答

5

嘗試了這一點:

public static class FocusBehavior 
{ 
    public static readonly DependencyProperty ClickKeyboardFocusTargetProperty = 
     DependencyProperty.RegisterAttached("ClickKeyboardFocusTarget", typeof(IInputElement), typeof(FocusBehavior), 
     new PropertyMetadata(OnClickKeyboardFocusTargetChanged)); 

    public static IInputElement GetClickKeyboardFocusTarget(DependencyObject obj) 
    { 
     return (IInputElement)obj.GetValue(ClickKeyboardFocusTargetProperty); 
    } 

    public static void SetClickKeyboardFocusTarget(DependencyObject obj, IInputElement value) 
    { 
     obj.SetValue(ClickKeyboardFocusTargetProperty, value); 
    } 

    private static void OnClickKeyboardFocusTargetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 
    { 
     var button = sender as ButtonBase; 
     if (button == null) 
      return; 

     if (e.OldValue == null && e.NewValue != null) 
      button.Click += OnButtonClick; 
     else if (e.OldValue != null && e.NewValue == null) 
      button.Click -= OnButtonClick; 
    } 

    private static void OnButtonClick(object sender, RoutedEventArgs e) 
    { 
     var target = GetKeyboardClickFocusTarget((ButtonBase)sender); 

     Keyboard.Focus(target); 
    } 
} 

然後使用它,

<TextBox x:Name="TargetTextBox"/> 
<Button b:FocusBehavior.ClickKeyboardFocusTarget="{Binding ElementName=TargetTextBox}"/> 
+0

謝謝,這給了我一個良好的開端! – devdigital 2011-01-15 14:26:09

相關問題