简体   繁体   English

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

[英]C# xaml WPF textbox losing focus automatically while typing

I have a textbox in xaml (well, several textboxes) that are behaving improperly. 我在xaml中有一个文本框(好几个文本框),它们的行为不正确。 When I set my focus to the textbox (with or without typing anything), after some time that particular textbox loses its focus automatically. 当我将焦点设置到文本框时(无论是否键入任何内容),一段时间后,该特定文本框都会自动失去焦点。 It happens fast for some textboxes whereas slow for some but occurs in all. 对于某些文本框,它发生得很快,而对于某些文本框,它发生得慢,但全部发生。 Its killing me for last 3 days but couldn't find anything. 最近三天它杀死了我,但找不到任何东西。 Its just a normal textbox. 它只是一个普通的文本框。 If anyone has any idea or possibilities behind this, please mention it. 如果有人对此有任何想法或可能性,请提及。

I have faced this issue too when I worked with complex GUI with a lot of lists, master-details, etc. Frankly, I didn't figure out what was the reason for this issue, but sometime focus just was lost during the typing. 当我使用带有大量列表,主细节等的复杂GUI时,我也遇到了这个问题。坦白地说,我没有弄清楚这个问题的原因是什么,但是有时在键入过程中就失去了焦点。 I fixed this problem with this behavior: 我通过以下行为解决了此问题:

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;
    }

}

Usage in XAML: 在XAML中的用法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM