gpt4 book ai didi

c# - 如何在没有 NoWrap 的情况下跟踪 TextBox 中文本的结尾?

转载 作者:行者123 更新时间:2023-11-30 14:45:22 26 4
gpt4 key购买 nike

我在 xaml 中有一个 TextBox:

<TextBox Name="Text" HorizontalAlignment="Left" Height="75"   VerticalContentAlignment="Center" TextWrapping="NoWrap" Text="TextBox" Width="336"  BorderBrush="Black" FontSize="40" />

我用这个方法给它添加文本:

private string words = "Initial text contents of the TextBox.";

public async void textRotation()
{
for(int a =0; a < words.Length; a++)
{
Text.Text = words.Substring(0,a);
await Task.Delay(500);
}
}

一旦文本脱离环绕,是否有一种方法可以使末尾聚焦,这样旧文本就会消失在左侧,新文本会出现在右侧,而不是只是将其添加到右侧而看不到。

最佳答案

一个快速的方法是用TextRenderer.MeasureText测量需要滚动的字符串(words) , 将 width 度量分成等于字符串中字符数的部分并使用 ScrollToHorizontalOffset()执行滚动:

public async void TextRotation()
{
float textPart = TextRenderer.MeasureText(words, new Font(Text.FontFamily.Source, (float)Text.FontSize)).Width / words.Length;
for (int i = 0; i < words.Length; i++)
{
Text.Text = words.Substring(0, i);
await Task.Delay(100);
Text.ScrollToHorizontalOffset(textPart * i);
}
}

相同,但使用 FormattedText测量字符串的类:

public async void TextRotation()
{
var textFormat = new FormattedText(
words, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight,
new Typeface(Text.FontFamily, Text.FontStyle, Text.FontWeight, Text.FontStretch),
Text.FontSize, null, null, 1);

float textPart = (float)textFormat.Width / words.Length;
for (int i = 0; i < words.Length; i++)
{
Text.Text = words.Substring(0, i);
await Task.Delay(200);
Text.ScrollToHorizontalOffset(textPart * i);
}
}

WPF scrolling text

关于c# - 如何在没有 NoWrap 的情况下跟踪 TextBox 中文本的结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53989719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com