asp.net WPF 走马灯 文字滚动 自定义控件

作者:袖梨 2022-06-25

代码如下 复制代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel;
using System.Drawing;
using System.Timers;
using System.Windows;

namespace WpfDemoNew.Control
{
///


/// Label走马灯自定义控件
///

[ToolboxBitmap(typeof(Label))] //设置工具箱中显示的图标
public class ScrollingTextControl:Label
{
///
/// 定时器
///

Timer MarqueeTimer = new Timer();
///
/// 滚动文字源
///

String _TextSource = "滚动文字源";
///
/// 输出文本
///

String _OutText = string.Empty;
///
/// 文字的滚动速度
///

double _RunSpeed = 1000;

///


/// 构造函数
///

public ScrollingTextControl()
{
MarqueeTimer.Interval = _RunSpeed;//文字移动的速度
MarqueeTimer.Enabled = true; //开启定时触发事件
MarqueeTimer.Elapsed += new ElapsedEventHandler(MarqueeTimer_Elapsed);//绑定定时事件
this.Loaded += new RoutedEventHandler(ScrollingTextControl_Loaded);//绑定控件Loaded事件
}


void ScrollingTextControl_Loaded(object sender, RoutedEventArgs e)
{
_TextSource = SetContent;
_OutText = _TextSource + " ";
}

void MarqueeTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (string.IsNullOrEmpty(_OutText)) return;
_OutText = _OutText.Substring(1) + _OutText[0];
Dispatcher.BeginInvoke(new Action(() => {
SetContent = _OutText;
}));
}

///


/// 滚动的速度
///

[Description("文字滚动的速度")] //显示在属性设计视图中的描述
public double RunSpeed
{
get { return _RunSpeed; }
set
{
_RunSpeed = value;
MarqueeTimer.Interval = _RunSpeed;
}
}

///


/// 滚动文字源
///

[Description("文字滚动的速度")]
public string TextSource
{
get { return _TextSource; }
set
{
_TextSource = value;
_OutText = _TextSource;
}
}

private string SetContent
{
get { return Content.ToString(); }
set
{
Content = value;
}
}
}
}

以上放到cs文件中 然后 编译 就可以在工具箱中看到ScrollingTextControl 名称的label控件

代码如下 复制代码

xmlns="http://schemas.m*i*cro*soft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.m*icr*oso*ft.com/winfx/2006/xaml"
Title="Window21" Height="300" Width="300" xmlns:my="clr-namespace:WpfDemoNew.Control">



相关文章

精彩推荐