我有一个模板化列表框,其中模板也包含一个 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>
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码适用于我滚动到 TextBox 的末尾(取自这个问题):
textBox.CaretIndex = textBox.Text.Length;
var rect = textBox.GetRectFromCharacterIndex(textBox.CaretIndex);
textBox.ScrollToHorizontalOffset(rect.Right);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4890 次 |
| 最近记录: |