c# WPF如何實(shí)現(xiàn)滾動顯示的TextBlock
在我們使用TextBlock進(jìn)行數(shù)據(jù)顯示時,經(jīng)常會遇到這樣一種情況就是TextBlock的文字內(nèi)容太多,如果全部顯示的話會占據(jù)大量的界面,這是我們就會只讓其顯示一部分,另外的一部分就讓其隨著時間的推移去滾動進(jìn)行顯示,但是WPF默認(rèn)提供的TextBlock是不具備這種功能的,那么怎么去實(shí)現(xiàn)呢?
其實(shí)個人認(rèn)為思路還是比較清楚的,就是自己定義一個UserControl,然后將WPF簡單的元素進(jìn)行組合,最終實(shí)現(xiàn)一個自定義控件,所以我們順著這個思路就很容易去實(shí)現(xiàn)了,我們知道Canvas這個控件可以通過設(shè)置Left、Top、Right、Bottom屬性去精確控制其子控件的位置,那么很顯然我們需要這一控件,另外我們在Canvas容器里面再放置TextBlock控件,并且設(shè)置TextWrapping="Wrap"讓其全部顯示所有的文字,當(dāng)然這里面既然要讓其滾動,那么TextBlock的高度肯定會超過Canvas的高度,這樣才有意義,另外一個重要的部分就是設(shè)置Canvas的ClipToBounds="True"這個屬性,這樣超過的部分就不會顯示,具體的實(shí)現(xiàn)思路參照代碼我再一步步去認(rèn)真分析!
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>
這里分析幾個重要的知識點(diǎn):A:DataContext="{Binding RelativeSource={RelativeSource Self}}" 這個為當(dāng)前的前臺綁定數(shù)據(jù)源,這個是第一步,同時也是基礎(chǔ)。B 為當(dāng)前的TextBlock綁定Text、Canvas.Left、Canvas.Top以及Width等屬性,當(dāng)然這些屬性要結(jié)合自己的需要去綁定,并在后臺定義相關(guān)的依賴項(xiàng)屬性。
然后再看看后臺的邏輯代碼:
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中的位置,這里面有一個知識點(diǎn)需要注意,如何獲取當(dāng)前TextBlock的ActualHeight,我們可以通過重寫基類的OnApplyTemplate這個方法來獲取,另外這個方法還是存在前臺和后臺的耦合,是否可以通過綁定來獲取TextBlock的ActualHeight,如果通過綁定應(yīng)該注意些什么?這其中需要特別注意的是ActualHeight表示的是元素重繪制后的尺寸,并且是只讀的,也就是說其始終是真實(shí)值,在綁定時是無法為依賴性屬性增加Set的,并且在綁定時綁定的模式只能夠是Mode=“OneWayToSource”而不是默認(rèn)的Mode=“TwoWay”。
另外在使用定時器時為什么使用System.Windows.Threading.DispatcherTimer而不是System.Timers.Timer?這個需要我們?nèi)フJ(rèn)真分析原因,只有這樣才能真正地去學(xué)會WPF。
當(dāng)然本文只是提供一種簡單的思路,后面還有很多可以擴(kuò)展的地方,比如每次移動的距離如何確定,移動的速率是多少?這個如果做豐富,是有很多的內(nèi)容,這個需要根據(jù)具體的項(xiàng)目需要去擴(kuò)展,這里只是提供最簡單的一種方式,僅僅提供一種思路。
2 如何引用當(dāng)前的自定義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="漢皇重色思傾國,御宇多年求不得。楊家有女初長成,養(yǎng)在深閨人未識。天生麗質(zhì)難自棄,一朝選在君王側(cè)。回眸一笑百媚生,六宮粉黛無顏色。春寒賜浴華清池,溫泉水滑洗凝脂。 侍兒扶起嬌無力,始是新承恩澤時。云鬢花顏金步搖,芙蓉帳暖度春宵。春宵苦短日高起,從此君王不早朝。" FontSize="22"> </local:RoilingTextBlock> </Grid> </Window>
3 最后來看看最終的效果,當(dāng)然數(shù)據(jù)是處于不斷滾動狀態(tài),這里僅僅貼出一張圖片。

以上就是c# WPF如何實(shí)現(xiàn)滾動顯示的TextBlock的詳細(xì)內(nèi)容,更多關(guān)于WPF實(shí)現(xiàn)滾動顯示的TextBlock的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C# 操作 access 數(shù)據(jù)庫的實(shí)例代碼
這篇文章主要介紹了C# 操作 access 數(shù)據(jù)庫的實(shí)例代碼,需要的朋友可以參考下2018-03-03
解決C# X64應(yīng)用程序中讀取WParam溢出的問題
C#應(yīng)用程序是AnyCPU的,在一段處理鼠標(biāo)滾輪WM_MOUSEWHEEL的代碼里碰到溢出的問題OverflowException2013-04-04
C#實(shí)現(xiàn)帶行數(shù)和標(biāo)尺的RichTextBox
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)帶行數(shù)和標(biāo)尺的RichTextBox,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12
C#中IList 與 List 的區(qū)別小結(jié)
IList 接口和 List 類是 C# 中用于集合操作的兩個重要的類型,本文主要介紹了C#中IList 與 List 的區(qū)別小結(jié),具有一定的參考價值,感興趣的可以了解一下2024-04-04
關(guān)于C#.net winform程序驗(yàn)證moss的集成身份認(rèn)證實(shí)例
因?yàn)榫W(wǎng)站使用的是windows集成認(rèn)證,所以遇到了權(quán)限問題,需要輸入密碼。使操作和用戶體驗(yàn)非常不方便,研究了好久沒有找到好的方法,最后終于讓我踏破鐵鞋總結(jié)出了下面的方法2013-03-03
C#使用PPT組件的CreateVideo方法實(shí)現(xiàn)視頻生成
這篇文章主要為大家詳細(xì)介紹了C#如何使用PPT組件的CreateVideo方法實(shí)現(xiàn)視頻生成,文中的示例代碼講解詳細(xì),有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-10-10

