0
votes

I have a textbox in xaml (well, several textboxes) that are behaving improperly. 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.

1
Without your code (or the most significative parts of it) it is almost impossible to help you - Il Vic
Does it work for you? - Mr.B

1 Answers

0
votes

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. 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:

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