2013-10-01 36 views
0

我有一個主窗口,其中有大量的用戶控件。並使用導航我能夠訪問用戶控件。但問題是如何在用戶控件打開時將注意力放在第一個文本框上。從WPF中的ViewModel設置TextBox的焦點

我試着用依賴屬性和布爾標誌,我能夠成功了一下。當我第一次渲染用戶控件時,我能夠進行對焦,但是當我第二次打開時,我無法將焦點置於文本框上。

還有一件事,我有文本框驗證,如果驗證失敗,那麼文本框應該清空,焦點應該在各自的文本框。

我怎樣才能做到這一點使用MVVM在WPF(CLR 3.5,VS2008)

在此先感謝。

回答

1

如果你有一個UserControl,那麼你也有CodeBehind。

把這個放在你的代碼隱藏之中,你會做的很好。

this.Loaded += (o, e) => { Keyboard.Focus(textBox1) } 

如果您希望收聽驗證錯誤,請將其放置在UserControl XAML中。

<UserControl> 
<Grid Validation.Error="OnValidationError"> 
    <TextBox Text{Binding ..., NotifyOnValidationError=true } /> 
</Grid> 
<UserControl> 

你的用戶控件的代碼隱藏在裏面你會是這樣的:

public void OnValidationError(o , args) 
{ 
    if(o is TextBox) 
    { 
    (TextBox)o).Text = string.Empty; 
    } 
} 
0

您應該使用AttachedProperty堅持MVVM模式,它會保持你的視圖模型獨立的UI代碼和完全單元測試。下面的附加屬性將綁定一個布爾屬性來聚焦並突出顯示TextBox,如果您不想突出顯示,那麼您可以刪除突出顯示的代碼並僅使用焦點代碼。

public class TextBoxBehaviors 
    { 
     #region HighlightTextOnFocus Property 

     public static readonly DependencyProperty HighlightTextOnFocusProperty = 
      DependencyProperty.RegisterAttached("HighlightTextOnFocus", typeof (bool), typeof (TextBoxBehaviors), 
               new PropertyMetadata(false, HighlightTextOnFocusPropertyChanged)); 

     public static bool GetHighlightTextOnFocus(DependencyObject obj) 
     { 
      return (bool) obj.GetValue(HighlightTextOnFocusProperty); 
     } 

     public static void SetHighlightTextOnFocus(DependencyObject obj, bool value) 
     { 
      obj.SetValue(HighlightTextOnFocusProperty, value); 
     } 

     private static void HighlightTextOnFocusPropertyChanged(DependencyObject sender, 
                   DependencyPropertyChangedEventArgs e) 
     { 
      var uie = sender as UIElement; 
      if (uie == null) return; 

      if ((bool) e.NewValue) 
      { 
       uie.GotKeyboardFocus += OnKeyboardFocusSelectText; 
       uie.PreviewMouseLeftButtonDown += OnMouseLeftButtonDownSetFocus; 
      } 
      else 
      { 
       uie.GotKeyboardFocus -= OnKeyboardFocusSelectText; 
       uie.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDownSetFocus; 
      } 
     } 

     private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e) 
     { 
      var textBox = sender as TextBox; 
      if (textBox == null) return; 

      textBox.SelectAll(); 
     } 

     private static void OnMouseLeftButtonDownSetFocus(object sender, MouseButtonEventArgs e) 
     { 
      var textBox = sender as TextBox; 
      if (textBox == null) return; 

      if (!textBox.IsKeyboardFocusWithin) 
      { 
       textBox.Focus(); 
       e.Handled = true; 
      } 
     } 

     #endregion 
    } 

您可以使用您的文本框要聚焦/亮點此附加屬性...

<TextBox ... local:TextBoxBehaviors.HighlightTextOnFocus="{Binding IsScrolledToEnd}" ... /> 
0

您也可以使用嘗試FocusManager

<UserControl> 
<Grid FocusManager.FocusedElement="{Binding Path=FocusedTextBox, ElementName=UserControlName}"> 
    <TextBox x:Name="FocusedTextBox" /> 
</Grid> 
<UserControl>