WPF实现滚动显示的TextBlock

时间:2022-06-22 05:45:07

  在我们使用TextBlock进行数据显示时,经常会遇到这样一种情况就是TextBlock的文字内容太多,如果全部显示的话会占据大量的界面,这是我们就会只让其显示一部分,另外的一部分就让其随着时间的推移去滚动进行显示,但是WPF默认提供的TextBlock是不具备这种功能的,那么怎么去实现呢?

  其实个人认为思路还是比较清楚的,就是自己定义一个UserControl,然后将WPF简单的元素进行组合,最终实现一个自定义控件,所以我们顺着这个思路就很容易去实现了,我们知道Canvas这个控件可以通过设置Left、Top、Right、Bottom属性去精确控制其子控件的位置,那么很显然我们需要这一控件,另外我们在Canvas容器里面再放置TextBlock控件,并且设置TextWrapping="Wrap"让其全部显示所有的文字,当然这里面既然要让其滚动,那么TextBlock的高度肯定会超过Canvas的高度,这样才有意义,另外一个重要的部分就是设置Canvas的ClipToBounds="True"这个属性,这样超过的部分就不会显示,具体的实现思路参照代码我再一步步去认真分析!

  1 新建一个UserControl,命名为RollingTextBlock。

<UserControl x:Class="TestRoilingTextBlock.RoilingTextBlock" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" DataContext="{Binding RelativeSource={RelativeSource Self}}" mc:Ignorable="d" d:DesignWidth="300"> <UserControl.Template> <ControlTemplate TargetType="UserControl"> <Border BorderBrush="Gray" BorderThickness="1" Padding="2" Background="Gray"> <Canvas x:Name="innerCanvas" Background="AliceBlue" ClipToBounds="True"> <TextBlock x:Name="textBlock" TextAlignment="Center" TextWrapping="Wrap" ClipToBounds="True" Canvas.Left="{Binding Left,Mode=TwoWay}" Canvas.Top="{Binding Top,Mode=TwoWay}" FontSize="{Binding FontSize,Mode=TwoWay}" Text="{Binding Text,Mode=TwoWay}" Foreground="{Binding Foreground,Mode=TwoWay}"> </TextBlock> </Canvas> </Border> </ControlTemplate> </UserControl.Template> </UserControl>

  这里分析几个重要的知识点:A:DataContext="{Binding RelativeSource={RelativeSource Self}}" 这个为当前的前台绑定数据源,这个是第一步,同时也是基础。B 为当前的TextBlock绑定Text、Canvas.Left、Canvas.Top以及Width等属性,当然这些属性要结合自己的需要去绑定,并在后台定义相关的依赖项属性。

然后再看看后台的逻辑代码:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace TestRoilingTextBlock { /// <summary> /// RoilingTextBlock.xaml 的交互逻辑 /// </summary> public partial class RoilingTextBlock : UserControl { private bool canRoll = false; private double rollingInterval = 16;//每一步的偏移量 private double offset=6;//最大的偏移量 private TextBlock currentTextBlock = null; private DispatcherTimer currentTimer = null; public RoilingTextBlock() { InitializeComponent(); Loaded += RoilingTextBlock_Loaded; } void RoilingTextBlock_Loaded(object sender, RoutedEventArgs e) { if (this.currentTextBlock != null) { canRoll = this.currentTextBlock.ActualHeight > this.ActualHeight; } currentTimer = new System.Windows.Threading.DispatcherTimer(); currentTimer.Interval = new TimeSpan(0, 0, 1); currentTimer.Tick += new EventHandler(currentTimer_Tick); currentTimer.Start(); } public override void OnApplyTemplate() { try { base.OnApplyTemplate(); currentTextBlock = this.GetTemplateChild("textBlock") as TextBlock; } catch (Exception ex) { } } void currentTimer_Tick(object sender, EventArgs e) { if (this.currentTextBlock != null && canRoll) { if (Math.Abs(Top) <= this.currentTextBlock.ActualHeight-offset) { Top-=rollingInterval; } else { Top = this.ActualHeight; } } } #region Dependency Properties public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(RoilingTextBlock), new PropertyMetadata("")); public static DependencyProperty FontSizeProperty = DependencyProperty.Register("FontSize", typeof(double), typeof(RoilingTextBlock), new PropertyMetadata(14D)); public static readonly DependencyProperty ForegroundProperty = DependencyProperty.Register("Foreground", typeof(Brush), typeof(RoilingTextBlock), new FrameworkPropertyMetadata(Brushes.Green)); public static DependencyProperty LeftProperty = DependencyProperty.Register("Left", typeof(double), typeof(RoilingTextBlock),new PropertyMetadata(0D)); public static DependencyProperty TopProperty = DependencyProperty.Register("Top", typeof(double), typeof(RoilingTextBlock),new PropertyMetadata(0D)); #endregion #region Public Variables public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public double FontSize { get { return (double)GetValue(FontSizeProperty); } set { SetValue(FontSizeProperty, value); } } public Brush Foreground { get { return (Brush)GetValue(ForegroundProperty); } set { SetValue(ForegroundProperty, value); } } public double Left { get { return (double)GetValue(LeftProperty); } set { SetValue(LeftProperty, value); } } public double Top { get { return (double)GetValue(TopProperty); } set { SetValue(TopProperty, value); } } #endregion } }