文本长度超过TextBox宽度后失去焦点后的TextBox和TextAlignment

时间:2011-09-12 10:24:27

标签: wpf textbox dispatcher alignment lostfocus

我有以下问题:我在WPF应用程序中有一个TextBox。当我输入一个非常长的文本(比文本框字段中显示的字符多) 而且远离那个文本框字段(例如,对于其他文本框),我刚输入的文本保持右对齐(我离开它的地方)。 换句话说,我不能再看到文本的开头,除非我点击Home键或关闭屏幕并再次打开它。 移动到窗口上的另一个文本框后,我可以将文本对齐到左侧。我尝试了最可能的“鱼”解决方案,它不起作用:

    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 个答案:

答案 0 :(得分:2)

试试这个:

 textBox.SelectionStart = 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上的用法。