最近在一个外网的网站,困扰了我多天的循环和大家分享下,也做为我以后工作之用.第一种(信息作用循环.实现方式后台时钟在前台循环滚动(左右)显示).
为了方便初学者我把实验代码的源码都公布了出来.
前台页面:
<UserControl x:Class="listScroll.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Canvas Name="canMain" Width="300" Height="300">
<TextBlock Name="tbmarquee"></TextBlock><!-- 用于循环信息显示之用-->
</Canvas>
<!-- 呈现自元素的容器 -->
</UserControl>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace listScroll
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
//产生时钟的模拟操作,同时把时间赋值给前台显示控件
this.tbmarquee.Text = string.Concat("TimerWindow ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
TopToBottomMarquee();
}
private void TopToBottomMarquee()
{
// 定义一个矩形,把循环的信息放在矩形中.
RectangleGeometry rectangleGeometry = new RectangleGeometry();
rectangleGeometry.Rect = new Rect(new Point(0, 0), new Size(canMain.Width, canMain.Height));
canMain.Clip = rectangleGeometry;
double width = canMain.Width - tbmarquee.ActualWidth;
double jleft = width/2;
tbmarquee.Margin = new Thickness(jleft, 0, 0, 0);
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = -tbmarquee.ActualHeight;
doubleAnimation.To = canMain.Height;
doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(1)); //循环时间
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(doubleAnimation);
Storyboard.SetTarget(doubleAnimation, tbmarquee);
Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Top)"));//Canvas.Top:上下信息循环显示,Canvas.Left :信息左右循环显示
storyboard.Begin();
}
}
}
如果转载请说明出处.