2011-09-12 124 views
1

我有以下問題:我在WPF應用程序中有一個TextBox。當我輸入的文本很長(比文本框字段中顯示的字符多) ,並且遠離該文本框字段(例如,轉到某個其他文本框),我輸入的文本保持不變 - 合理(我離開了它)。 換句話說,除非我按Home鍵或關閉屏幕並再次打開,否則我不能再看到文本的開頭。 移動到窗口上的其他文本框後,可以將文本對齊到左邊嗎?我試圖用一個最有可能「魚」解決方案,這是行不通的:TextBox和TextAlignment失去焦點後,當文本長於TextBox寬度

private void TextEditControl_LostFocus(object sender, RoutedEventArgs e) 
    { 
     var textBox = sender as TextBox; 
     if (textBox != null) 
     { 
      textBox.Dispatcher.BeginInvoke(
       DispatcherPriority.Send, 
       new Action(() => SendKeys.SendWait("{HOME}"))); 
     } 
    } 

回答

2

試試這個:

textBox.SelectionStart = 0; 
+0

+1,在一個側面說明,可以很容易地變成一個附加的行爲的可重用性 –

1

按Meleak對添水壩的答案紙條,這裏是你如何做到這一點的附加的行爲:

using System.Windows; 
using System.Windows.Controls; 

public static class TextBoxBehavior 
{ 
    public static bool GetHomeOnLostFocus(DependencyObject obj) 
    { 
     return (bool)obj.GetValue(HomeOnLostFocusProperty); 
    } 

    public static void SetHomeOnLostFocus(DependencyObject obj, bool value) 
    { 
     obj.SetValue(HomeOnLostFocusProperty, value); 
    } 

    // Using a DependencyProperty as the backing store for HomeOnLostFocus. 
    // This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty HomeOnLostFocusProperty = 
     DependencyProperty.RegisterAttached(
      "HomeOnLostFocus", 
      typeof(bool), 
      typeof(TextBoxBehavior), 
      new UIPropertyMetadata(false, OnHomeOnLostFocusChanged)); 

    public static void OnHomeOnLostFocusChanged(
     DependencyObject d, 
     DependencyPropertyChangedEventArgs e) 
    { 
     // Type checking and casting of parameters 
     bool oldVal = (bool)e.OldValue; 
     bool newVal = (bool)e.NewValue; 
     TextBox textBox = d as TextBox; 

     // Argument value tests 
     if (textBox == null) return; 
     if (oldVal == newVal) return; 

     // If HomeOnLostFocus then add event handler, otherwise, remove it. 
     if (newVal) 
      textBox.LostFocus += TextBox_LostFocus; 
     else 
      textBox.LostFocus -= TextBox_LostFocus; 
    } 

    static void TextBox_LostFocus(object sender, RoutedEventArgs e) 
    { 
     var textBox = (TextBox)sender; 
     textBox.SelectionStart = 0; 
    } 
} 

需要引用PresentationCorePresentationFrameworkSystem.XamlWindowsBase組件。

下面是使用例子:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:tbb="clr-namespace:TextBoxBehavior;assembly=TextBoxBehavior" 
     Title="MainWindow" Height="350" Width="525"> 
    <StackPanel> 
     <TextBox Width="200"/> 
     <TextBox tbb:TextBoxBehavior.HomeOnLostFocus="true" Width="200"/> 
     <Button Content="Dummy" Width="200"/> 
    </StackPanel> 
</Window> 

注意xmlns:tbb屬性及其二號TextBox使用。

+0

Uf ...非常感謝你...它的工作! – SebastijanP