4

我有一个可编辑的组合框,当添加的文本太长时,它看起来像这样:

在此处输入图像描述

如何使文本框从字符串的开头开始?

TextBox txt = sender as TextBox;
txt.Text = "[Children]";

    <Style TargetType="TextBox">
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="BorderBrush" Value="Silver"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="AllowDrop" Value="true"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBoxBase}">
                    <Border Name="Border" Padding="1" Background="#FFFFFF" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" >
                        <ScrollViewer Margin="0" x:Name="PART_ContentHost"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter TargetName="Border" Property="Background" Value="#EEEEEE"/>
                            <Setter TargetName="Border" Property="BorderBrush" Value="#EEEEEE"/>
                            <Setter Property="Foreground" Value="#888888"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

组合框:

ComboBox cmbValue1 = new ComboBox();
cmbValue1.IsTextSearchEnabled = false;
cmbValue1.IsEditable = true;
cmbValue1.Width = 70;
TextBox txtEdit = (TextBox)((sender as ComboBox).Template.FindName("PART_EditableTextBox", (sender as ComboBox)));
txtEdit.Tag = selection;
4

1 回答 1

0

您需要将选择开始设置回 0,以便在用户输入内容后使其“左对齐”。

通过TextBoxBase.PreviewLostKeyboardFocus事件执行此操作 - 这是一些 XAML:

 <ComboBox Name="ComboBox1"
           IsEditable="True" 
           TextBoxBase.PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus_1">

而事件本身:

private void TextBox_PreviewLostKeyboardFocus_1(object sender, KeyboardFocusChangedEventArgs e)
{
    TextBox txtEdit = (TextBox)((sender as ComboBox).Template.FindName("PART_EditableTextBox", (sender as ComboBox)));
    txtEdit.SelectionStart = 0;
}

我认为这应该足以让您适应您的应用程序。我在一个空的 WPF 应用程序中进行了测试,无论您是按 TAB 还是用鼠标单击 UI 的另一部分,它都可以正常工作。

编辑:

以下是在代码中添加事件的方法:

不确定您的应用程序的结构如何,但同样,这对我有用:

private void Window_Initialized_1(object sender, EventArgs e)
{
    ComboBox cmbValue1 = new ComboBox();
    cmbValue1.IsTextSearchEnabled = false;
    cmbValue1.IsEditable = true;
    cmbValue1.Width = 70;
    cmbValue1.PreviewLostKeyboardFocus += TextBox_PreviewLostKeyboardFocus_1;

    this.MyCanvas.Children.Add(cmbValue1);
}

(使用我在这个答案上面发布的相同事件处理程序)

编辑:

这是工作项目的链接: 注意——如果在您失去焦点时(即,在您键入内容或取消选择之后)未选择可编辑 ComboBox 中的文本,它会起作用。我会尝试解决这个问题。

http://23.23.250.9/wpfresource.zip
于 2013-03-20T12:03:33.377 回答