C#xaml WPF文本框在键入时自动失去焦点

时间:2016-09-14 12:05:39

标签: c# wpf xaml textbox focus

我在xaml(好吧,几个文本框)中有一个文本框,表现不正常。当我将焦点设置到文本框(有或没有键入任何内容)时,一段时间后特定文本框会自动失去焦点。对于某些文本框来说,它发生得很快,而对于某些文本框来说,它会很慢它杀了我最近3天却找不到任何东西。它只是一个普通的文本框。如果有人对此有任何想法或可能性,请提及它。

1 个答案:

答案 0 :(得分:0)

当我使用包含大量列表,主要细节等的复杂GUI时,我也遇到过这个问题。坦率地说,我没有弄清楚这个问题的原因是什么,但有时焦点只是打字时输了。 我用这种行为修复了这个问题:

public class TextBoxBehaviors
{
    public static bool GetEnforceFocus(DependencyObject obj)
    {
        return (bool)obj.GetValue(EnforceFocusProperty);
    }

    public static void SetEnforceFocus(DependencyObject obj, bool value)
    {
        obj.SetValue(EnforceFocusProperty, value);
    }

    // Using a DependencyProperty as the backing store for EnforceFocus.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EnforceFocusProperty =
        DependencyProperty.RegisterAttached("EnforceFocus", typeof(bool), typeof(TextBoxBehaviors), new PropertyMetadata(false,
             (o, e) =>
             {
                 bool newValue = (bool)e.NewValue;
                 if (!newValue) return;

                 TextBox tb = o as TextBox;

                 if (tb == null)
                 {
                     MessageBox.Show("Target object should be typeof TextBox only. Execution has been seased", "TextBoxBehaviors warning",
                       MessageBoxButton.OK, MessageBoxImage.Warning);
                 }

                 tb.TextChanged += OnTextChanged;

             }));

    private static void OnTextChanged(object o, TextChangedEventArgs e)
    {
        TextBox tb = o as TextBox;
        tb.Focus();
       /* You have to place your caret at the end of your text manually, because each focus repalce your caret at the beging of text.*/
        tb.CaretIndex = tb.Text.Length;
    }

}

XAML中的用法:

 <TextBox x:Name="txtPresenter"
             behaviors:TextBoxBehaviors.EnforceFocus="True"
             Text="{Binding Path=MyPath, UpdateSourceTrigger=PropertyChanged}"
             VerticalAlignment="Center" />