8
我想要在我的視圖上單擊按鈕時將鍵盤焦點設置爲文本框。我不想使用任何代碼隱藏,所以想知道是否有人編寫了附加的屬性或類似的解決方案?使用MVVM將焦點設置到WPF中的控件
我想要在我的視圖上單擊按鈕時將鍵盤焦點設置爲文本框。我不想使用任何代碼隱藏,所以想知道是否有人編寫了附加的屬性或類似的解決方案?使用MVVM將焦點設置到WPF中的控件
嘗試了這一點:
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}"/>
謝謝,這給了我一個良好的開端! – devdigital 2011-01-15 14:26:09