单行wpf文本框水平滚动到结尾

时间:2012-06-27 18:10:13

标签: c# wpf listbox

我有一个模板化的列表框,其中的模板也包含一个wpf文本框。数据通过ItemsSource提供给列表框。

文本框显示文件路径,这些通常很长。我想在加载文本框时显示文件路径的结尾。

我尝试了DataContextChanged事件和设置HorizontalScrollBarVisibility的组合(使用double.max或获取真正的字符长度),但没有成功。 DataContextChanged似乎是在ItemsSource的每个设置上触发时使用的正确事件。

编辑:

以下示例代码显示Lester的建议何时起作用以及何时起作用。我试图通过绑定设置文本时使其工作。

<Window x:Class="WpfAppTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    Loaded="LoadedHandler">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBox Name="tbb" Width="50" Height="20" Text="{Binding Path=Str}"
             IsReadOnly="True" Grid.Column="0" Grid.Row="0"
             DataContextChanged="ContextChangedHandler"/>
    <ListBox SelectionMode="Single" x:Name="listBox" Grid.Column="0" Grid.Row="1"
             VerticalAlignment="Top">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBox Width="50" Height="20" Text="{Binding Path=Str}"
                         IsReadOnly="True"
                         DataContextChanged="ContextChangedHandler"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent(); 

        var obj = new SomeClass
                      {
                          Str = "qwetyuiuropqo[psdal;dkas;ldamzxn m,cnz128391"
                      };
        listBox.ItemsSource = new List<SomeClass> { obj };
        tbb.DataContext = obj;
    }

    public class SomeClass
    {
        public string Str { get; set; }
    }

    private void LoadedHandler(object sender, RoutedEventArgs e)
    {
        var obj = new SomeClass
        {
            Str = "qwetyuiuropqo[psdal;dkas;ldamzxn m,cnz128391"
        };
        listBox.ItemsSource = new List<SomeClass> { obj };
        tbb.DataContext = obj;
    }

    private void ContextChangedHandler(object sender, DependencyPropertyChangedEventArgs e)
    {
        var textBox = sender as TextBox;
        if (textBox == null) return;

        textBox.CaretIndex = textBox.Text.Length;
        var rect = textBox.GetRectFromCharacterIndex(textBox.CaretIndex);
        textBox.ScrollToHorizontalOffset(rect.Right);
    }
}

2 个答案:

答案 0 :(得分:3)

此代码适用于滚动到TextBox的末尾(取自this question):

textBox.CaretIndex = textBox.Text.Length;
var rect = textBox.GetRectFromCharacterIndex(textBox.CaretIndex);
textBox.ScrollToHorizontalOffset(rect.Right);

答案 1 :(得分:0)

解决方案是使用Loaded更改DataContextChanged事件,以便收到文本框的正确通知。

相关问题