问题
I'm currently building an application for raspberry Pi (windows IoT) which accepts UDP messages and shows them on the screen.
I need a way to make the text horizontally scroll over the screen automatically. I can't let the user click a button because there are no input devices connected to the Pi.
So far I've been toying around with a scrollviewer and adjusting it's HorizontalAlignment value manually, but with no avail (I'm kinda new to the whole UWP/XAML stuff).
Can anyone show me some code that would make the text in the textblock automatically scroll from right to left (much in the way text scrolls on digital displays) that doesn't interrupt any of the other code running in the app (receiving udp messages and ticking the timer)?
Many thanks in advance.
回答1:
You can set the TextBlock
inside of a ScrollViewer
so can it to be scrolled for example like this:
<ScrollViewer x:Name="scrollviewer" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Hidden"
VerticalScrollMode="Disabled" HorizontalScrollMode="Enabled" Grid.Row="1" Loaded="scrollViewer_Loaded"
Unloaded="scrollviewer_Unloaded">
<TextBlock Text="Start:111fdafdilgklnkghiogj2222213135aaaadjiosfuiafkhafuia464676541134564132145546afafkjarpikfsanjahfnvfnvjkhghga:End" TextWrapping="NoWrap"
FontSize="40" />
</ScrollViewer>
And in the code behind use a DispatcherTimer
to set a timer for scrolling, in the Loaded event
of the ScrollViewer
start this timer and in the Unloaded event
of the ScrollViewer
stop this timer:
private void scrollViewer_Loaded(object sender, RoutedEventArgs e)
{
timer.Tick += (ss, ee) =>
{
if (timer.Interval.Ticks == 300)
{
//each time set the offset to scrollviewer.HorizontalOffset + 5
scrollviewer.ScrollToHorizontalOffset(scrollviewer.HorizontalOffset + 5);
//if the scrollviewer scrolls to the end, scroll it back to the start.
if (scrollviewer.HorizontalOffset == scrollviewer.ScrollableWidth)
scrollviewer.ScrollToHorizontalOffset(0);
}
};
timer.Interval = new TimeSpan(300);
timer.Start();
}
private void scrollviewer_Unloaded(object sender, RoutedEventArgs e)
{
timer.Stop();
}
Noticed your app is for raspberry Pi, just tested this code on RP2, OS version 10.0.14376.0, it works fine.
回答2:
See this post: Multiline Textbox with automatic vertical scroll
Replace the TextBlock with a readonly TextBox, so you can programmatically scroll to the end at each update of his content.
来源:https://stackoverflow.com/questions/38433555/c-sharp-uwp-autoscrolling-text