1

我有以下问题:我在 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}")));
        }
    }
4

2 回答 2

2

尝试这个:

 textBox.SelectionStart = 0;
于 2011-09-12T10:40:15.777 回答
1

根据 Meleak 关于 Tim Dams 答案的注释,以下是作为附加行为的方法:

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

需要对PresentationCorePresentationFramework和程序集System.Xaml的引用WindowsBase

这是使用示例:

<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:tbb2nd 的属性及其用法TextBox

于 2011-09-12T11:41:03.927 回答