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

以上就是c# WPF如何實(shí)現(xiàn)滾動(dòng)顯示的TextBlock的詳細(xì)內(nèi)容,更多關(guān)于WPF實(shí)現(xiàn)滾動(dòng)顯示的TextBlock的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#結(jié)合JavaScript實(shí)現(xiàn)多文件上傳功能
在許多應(yīng)用場(chǎng)景里,多文件上傳是一項(xiàng)比較實(shí)用的功能,本文主要為大家詳細(xì)介紹了C#如何結(jié)合JavaScript實(shí)現(xiàn)多文件上傳功能,感興趣的小伙伴可以了解下2023-12-12
C#對(duì)二進(jìn)制數(shù)據(jù)進(jìn)行base64編碼的方法
這篇文章主要介紹了C#對(duì)二進(jìn)制數(shù)據(jù)進(jìn)行base64編碼的方法,涉及C#中Convert.ToBase64String用法技巧,需要的朋友可以參考下2015-04-04
Jquery+Ajax+Json+存儲(chǔ)過程實(shí)現(xiàn)高效分頁(yè)
這篇文章主要介紹Jquery+Ajax+Json+存儲(chǔ)過程實(shí)現(xiàn)分頁(yè),需要的朋友可以參考下2015-08-08
C# Stream 和 byte[] 之間的轉(zhuǎn)換
Stream 和 byte[] 之間的轉(zhuǎn)換2008-03-03
如何用C#在PC上查找連接藍(lán)牙設(shè)備并實(shí)現(xiàn)數(shù)據(jù)傳輸
這篇文章主要介紹了如何用C#在PC上查找連接藍(lán)牙設(shè)備并實(shí)現(xiàn)數(shù)據(jù)傳輸,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03

