我在xaml
有一个文本框:
<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);
}
}
一旦文本从包装中移出,就有一种方法可以聚焦末端,使旧文本消失在左边,新文本消失在右边,而不是仅仅将其添加到右边而不会看到。
一个快速的方法是测量需要使用words
滚动的字符串(TextRenderer.MeasureText),将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(this.Text.FontFamily, this.Text.FontStyle, this.Text.FontWeight, this.Text.FontStretch),
this.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);
}
}
它应该相当容易实现,尝试添加此代码:
public async void textRotation()
{
for(int a =0; a < words.Length; a++)
{
Text.Text = words.Substring(0,a);
Text.ScrollToHorizontalOffset(Text.Text.Last());
await Task.Delay(500);
}
}