2016-09-14 77 views
0

我在XAML中有一个文本框(当然,一些文本框),这些行为不当。当我将注意力集中到文本框(有或没有输入任何内容)时,经过一段时间后,特定文本框会自动失去焦点。对于某些文本框,它发生得很快,而对于一些文本框却很慢,但总是发生。它在过去3天里杀了我,但找不到任何东西。它只是一个普通的文本框。如果任何人有任何想法或背后的可能性,请提及它。C#WPF XAML自动文本框失去焦点而打字

+2

没有你的代码(或它的最有意义的部分),这几乎是不可能帮你 –

+0

是否为工作您? –

回答

0

我面临这个问题太时,我曾与复杂的GUI有很多表,主信息等坦率地说,我也没搞清楚什么是这个问题的原因,但有时只专注迷路了在打字过程中。 我解决了这个问题,此行为:在XAML

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

} 

用法:

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

对于漫长的等待回应感到抱歉,但它对我无效。谢谢你的信息先生。 B.你对此有任何其他想法吗? –

+0

尝试发布代码段。 –

+0

其实我所做的就是,我创建TextBoxBehaviors类如上准确,在文本框,我用行为:TextBoxBehaviors.EnforceFocus =“真”。此外,还有一件事,当我打开文本框所在的对话框时,首先我将焦点放在该文本框上并等待5秒钟,然后文本框焦点丢失。我认为你的情况只适用于textboxchanged的情况,对吗?也许我错过了一些东西。 –