欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c# WPF如何實現(xiàn)滾動顯示的TextBlock

 更新時間:2021年03月02日 08:54:45   作者:Hello 尋夢者!  
這篇文章主要介紹了c# WPF如何實現(xiàn)滾動顯示的TextBlock,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下

  在我們使用TextBlock進行數(shù)據(jù)顯示時,經(jīng)常會遇到這樣一種情況就是TextBlock的文字內(nèi)容太多,如果全部顯示的話會占據(jù)大量的界面,這是我們就會只讓其顯示一部分,另外的一部分就讓其隨著時間的推移去滾動進行顯示,但是WPF默認提供的TextBlock是不具備這種功能的,那么怎么去實現(xiàn)呢?

  其實個人認為思路還是比較清楚的,就是自己定義一個UserControl,然后將WPF簡單的元素進行組合,最終實現(xiàn)一個自定義控件,所以我們順著這個思路就很容易去實現(xiàn)了,我們知道Canvas這個控件可以通過設置Left、Top、Right、Bottom屬性去精確控制其子控件的位置,那么很顯然我們需要這一控件,另外我們在Canvas容器里面再放置TextBlock控件,并且設置TextWrapping="Wrap"讓其全部顯示所有的文字,當然這里面既然要讓其滾動,那么TextBlock的高度肯定會超過Canvas的高度,這樣才有意義,另外一個重要的部分就是設置Canvas的ClipToBounds="True"這個屬性,這樣超過的部分就不會顯示,具體的實現(xià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>

  這里分析幾個重要的知識點:A:DataContext="{Binding RelativeSource={RelativeSource Self}}" 這個為當前的前臺綁定數(shù)據(jù)源,這個是第一步,同時也是基礎。B 為當前的TextBlock綁定Text、Canvas.Left、Canvas.Top以及Width等屬性,當然這些屬性要結(jié)合自己的需要去綁定,并在后臺定義相關(guān)的依賴項屬性。

     然后再看看后臺的邏輯代碼:

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?這個需要我們?nèi)フJ真分析原因,只有這樣才能真正地去學會WPF。

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

  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="漢皇重色思傾國,御宇多年求不得。楊家有女初長成,養(yǎng)在深閨人未識。天生麗質(zhì)難自棄,一朝選在君王側(cè)?;仨恍Π倜纳?,六宮粉黛無顏色。春寒賜浴華清池,溫泉水滑洗凝脂。
                                侍兒扶起嬌無力,始是新承恩澤時。云鬢花顏金步搖,芙蓉帳暖度春宵。春宵苦短日高起,從此君王不早朝。"
                                FontSize="22">           
        </local:RoilingTextBlock>
 
    </Grid>
</Window>

  3 最后來看看最終的效果,當然數(shù)據(jù)是處于不斷滾動狀態(tài),這里僅僅貼出一張圖片。

以上就是c# WPF如何實現(xiàn)滾動顯示的TextBlock的詳細內(nèi)容,更多關(guān)于WPF實現(xiàn)滾動顯示的TextBlock的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 淺談c#中const與readonly區(qū)別

    淺談c#中const與readonly區(qū)別

    C#引入了readonly修飾符來表示只讀域,const來表示不變常量。顧名思義對只讀域不能進行寫操作,不變常量不能被修改,這兩者到底有什么區(qū)別呢?
    2015-06-06
  • 基于C#實現(xiàn)宿舍管理系統(tǒng)

    基于C#實現(xiàn)宿舍管理系統(tǒng)

    這篇文章主要介紹了如何利用C#語言開發(fā)一個簡易的宿舍管理系統(tǒng),文中的實現(xiàn)步驟講解詳細,對我們學習C#有一定參考價值,感興趣的可以了解一下
    2022-06-06
  • C#結(jié)合JavaScript實現(xiàn)多文件上傳功能

    C#結(jié)合JavaScript實現(xiàn)多文件上傳功能

    在許多應用場景里,多文件上傳是一項比較實用的功能,本文主要為大家詳細介紹了C#如何結(jié)合JavaScript實現(xiàn)多文件上傳功能,感興趣的小伙伴可以了解下
    2023-12-12
  • C#處理TCP數(shù)據(jù)的方法詳解

    C#處理TCP數(shù)據(jù)的方法詳解

    Tcp是一個面向連接的流數(shù)據(jù)傳輸協(xié)議,用人話說就是傳輸是一個已經(jīng)建立好連接的管道,數(shù)據(jù)都在管道里像流水一樣流淌到對端,那么數(shù)據(jù)必然存在幾個問題,比如數(shù)據(jù)如何持續(xù)的讀取,數(shù)據(jù)包的邊界等,本文給大家介紹了C#處理TCP數(shù)據(jù)的方法,需要的朋友可以參考下
    2024-06-06
  • C#對二進制數(shù)據(jù)進行base64編碼的方法

    C#對二進制數(shù)據(jù)進行base64編碼的方法

    這篇文章主要介紹了C#對二進制數(shù)據(jù)進行base64編碼的方法,涉及C#中Convert.ToBase64String用法技巧,需要的朋友可以參考下
    2015-04-04
  • 如何在C#中使用注冊表

    如何在C#中使用注冊表

    這篇文章主要介紹了如何在C# 使用注冊表,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2020-12-12
  • Jquery+Ajax+Json+存儲過程實現(xiàn)高效分頁

    Jquery+Ajax+Json+存儲過程實現(xiàn)高效分頁

    這篇文章主要介紹Jquery+Ajax+Json+存儲過程實現(xiàn)分頁,需要的朋友可以參考下
    2015-08-08
  • C# Stream 和 byte[] 之間的轉(zhuǎn)換

    C# Stream 和 byte[] 之間的轉(zhuǎn)換

    Stream 和 byte[] 之間的轉(zhuǎn)換
    2008-03-03
  • 如何用C#在PC上查找連接藍牙設備并實現(xiàn)數(shù)據(jù)傳輸

    如何用C#在PC上查找連接藍牙設備并實現(xiàn)數(shù)據(jù)傳輸

    這篇文章主要介紹了如何用C#在PC上查找連接藍牙設備并實現(xiàn)數(shù)據(jù)傳輸,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下
    2021-03-03
  • C#實現(xiàn)百度ping推送功能的方法

    C#實現(xiàn)百度ping推送功能的方法

    百度ping是網(wǎng)站優(yōu)化必做的事情,這樣才能主動推送給百度,那么基于代碼是如何實現(xiàn)百度推送方法呢?下文小編給大家?guī)砹薈#實現(xiàn)百度ping推送功能的方法,非常不錯,感興趣的朋友一起學習吧
    2016-08-08

最新評論