2011-09-12 37 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