c# WPF如何實現滾動顯示的TextBlock

  在我們使用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" Height="136" Width="400">
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <Border BorderBrush="Gray"
                    BorderThickness="1"
                    Padding="2"
                    Background="Gray">
                <Canvas x:Name="innerCanvas"
                        Width="Auto"
                        Height="Auto"
                        Background="AliceBlue"
                        ClipToBounds="True">
                    <TextBlock x:Name="textBlock"
                               Width="{Binding ActualWidth,ElementName=innerCanvas}" 
                               TextAlignment="Center"
                               TextWrapping="Wrap"
                               Height="Auto"
                               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
    }
}

  再看後臺的代碼,這裡我們隻是通過一個定時器每隔1秒鐘去更新TextBlock在Canvas中的位置,這裡面有一個知識點需要註意,如何獲取當前TextBlock的ActualHeight,我們可以通過重寫基類的OnApplyTemplate這個方法來獲取,另外這個方法還是存在前臺和後臺的耦合,是否可以通過綁定來獲取TextBlock的ActualHeight,如果通過綁定應該註意些什麼?這其中需要特別註意的是ActualHeight表示的是元素重繪制後的尺寸,並且是隻讀的,也就是說其始終是真實值,在綁定時是無法為依賴性屬性增加Set的,並且在綁定時綁定的模式隻能夠是Mode=“OneWayToSource”而不是默認的Mode=“TwoWay”。

  另外在使用定時器時為什麼使用System.Windows.Threading.DispatcherTimer而不是System.Timers.Timer?這個需要我們去認真分析原因,隻有這樣才能真正地去學會WPF。

  當然本文隻是提供一種簡單的思路,後面還有很多可以擴展的地方,比如每次移動的距離如何確定,移動的速率是多少?這個如果做豐富,是有很多的內容,這個需要根據具體的項目需要去擴展,這裡隻是提供最簡單的一種方式,僅僅提供一種思路。

  2 如何引用當前的自定義RollingTextBlock?

<Window x:Class="TestRoilingTextBlock.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestRoilingTextBlock"
        Title="MainWindow" Height="550" Width="525">
    <Grid>
        <local:RoilingTextBlock Foreground="Teal"
                                Text="漢皇重色思傾國,禦宇多年求不得。楊傢有女初長成,養在深閨人未識。天生麗質難自棄,一朝選在君王側。回眸一笑百媚生,六宮粉黛無顏色。春寒賜浴華清池,溫泉水滑洗凝脂。
                                侍兒扶起嬌無力,始是新承恩澤時。雲鬢花顏金步搖,芙蓉帳暖度春宵。春宵苦短日高起,從此君王不早朝。"
                                FontSize="22">           
        </local:RoilingTextBlock>
 
    </Grid>
</Window>

  3 最後來看看最終的效果,當然數據是處於不斷滾動狀態,這裡僅僅貼出一張圖片。

以上就是c# WPF如何實現滾動顯示的TextBlock的詳細內容,更多關於WPF實現滾動顯示的TextBlock的資料請關註WalkonNet其它相關文章!

推薦閱讀: