2016-09-14 76 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的情況,對嗎?也許我錯過了一些東西。 –