WPF 簡易的跑馬燈效果

来源:http://www.cnblogs.com/ZXdeveloper/archive/2017/05/31/6925228.html
-Advertisement-
Play Games

最近項目上要用到跑馬燈的效果,和網上不太相同的是,網上大部分都是連續的,而我們要求的是不連續的。 也就是是,界面上就展示4項(展示項數可變),如果有7項要展示的話,則不斷的在4個空格裡左跳,當然,銜接上效果不是很好看。 然後,需要支持點擊以後進行移除掉不再顯示的內容。 效果如下: 思路大致如下: 1 ...


最近項目上要用到跑馬燈的效果,和網上不太相同的是,網上大部分都是連續的,而我們要求的是不連續的。

也就是是,界面上就展示4項(展示項數可變),如果有7項要展示的話,則不斷的在4個空格裡左跳,當然,銜接上效果不是很好看。

然後,需要支持點擊以後進行移除掉不再顯示的內容。

效果如下:

思路大致如下:

1、最外層用一個ViewBox,為了可以填充調用此控制項的地方,這樣可以方便自動拉伸

<Viewbox x:Name="viewbox_main" Height="{Binding Path=ActualHeight}" Width="{Binding Path=ActualWidth}" MouseLeave="grid_main_MouseLeave" MouseMove="grid_main_MouseMove"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Stretch="Fill"/>

2、定義三個變數,一個是Count值,是為了設定要展示的UserControl的個數的,例如預設是4個,如效果圖,當然,設置成5的話,就是5個了;一個List<Grid>是為了放入展示控制項的列表,一個List<UserControl>是用來放所有要用於跑馬燈里的控制項的。

3、設置一個Canvas,放入到最外層的Viewbox中,用於跑馬燈時候用(這也是常用的跑馬燈控制項Canvas)

//給Canvas設置一些屬性
 canvas_board.VerticalAlignment = VerticalAlignment.Stretch;
 canvas_board.HorizontalAlignment = HorizontalAlignment.Stretch;
canvas_board.Width = this.viewbox_main.ActualWidth;
canvas_board.Height = this.viewbox_main.ActualHeight;
canvas_board.ClipToBounds = true;
//用viewbox可以支持拉伸
this.viewbox_main.Child = canvas_board;

4、將要迴圈的Grid放入到Canvas里,這裡的Grid的個數,要比展示的個數大一個,也就是Count+1個值,因為滾動的時候,其實是在最外面有一個的,這樣保證了迴圈的走動。至於兩個控制項之間的Margin這個就是要設置Grid的了,到時候控制項是直接扔進Grid里的

//迴圈將Grid加入到要展示的列表裡
for (int i = 0; i < Uc_Count + 1; i++)
{
    Grid grid = new Grid();
    grid.Width = canvas_board.Width / Uc_Count - 10;
    grid.Height = canvas_board.Height - 10;
    grid.Margin = new Thickness(5);
    this.canvas_board.Children.Add(grid);
    grid.SetValue(Canvas.TopProperty, 0.0);
    grid.SetValue(Canvas.LeftProperty, i * (grid.Width + 10));

    UcListForShow.Add(grid);
}

5、給每個Grid增加一個動畫效果,就是向左移動的效果

for (int i = 0; i < UcListForShow.Count; i++)
{
    //設置滾動時候的效果
    DoubleAnimationUsingKeyFrames daukf_uc = new DoubleAnimationUsingKeyFrames();
    LinearDoubleKeyFrame k1_uc = new LinearDoubleKeyFrame(i * (UcListForShow[i].Width + 10), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)));
    LinearDoubleKeyFrame k2_uc = new LinearDoubleKeyFrame((i - 1) * (UcListForShow[i].Width + 10), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2.5)));
    daukf_uc.KeyFrames.Add(k1_uc);
    daukf_uc.KeyFrames.Add(k2_uc);
    storyboard_imgs.Children.Add(daukf_uc);
    Storyboard.SetTarget(daukf_uc, UcListForShow[i]);
    Storyboard.SetTargetProperty(daukf_uc, new PropertyPath("(Canvas.Left)"));
}

6、滾動的時候,要計算UserControl到底是添加到了哪個Grid裡面,也就是哪個控制項作為了第一位。

我們設置一個索引值scroll_index,預設的時候,scroll_index=0,這是初始的狀態,當滾動起來以後,scroll_index = scroll_index + 1 - Uc_Count;

然後,判斷,迴圈的時候,是否是展示列表的末尾了,如果是的話,則要填充的控制項是scroll_index %UcListSum.Count(滾動索引,對總數直接取餘數),如果不是的話則是scroll_index++ % UcListSum.Count(滾動索引++,對總數直接取餘數)

scroll_index = scroll_index + 1 - Uc_Count;

for (int i = 0; i < UcListForShow.Count; i++)
{
    UcListForShow[i].SetValue(Canvas.LeftProperty, i * (UcListForShow[i].Width + 10));
    UserControl uc;
    if (i == UcListForShow.Count - 1)
    {
        uc = UcListSum[scroll_index % UcListSum.Count];
    }
    else
    {
        uc = UcListSum[scroll_index++ % UcListSum.Count];
    }
    if (uc.Parent != null)
    {
        (uc.Parent as Grid).Children.Clear();//將Usercontrol從原來的裡面移除掉,要不然會拋錯,Usercontrol已屬於另一個控制項
    }
    UcListForShow[i].Children.Clear();
    UcListForShow[i].Children.Add(uc);
    //將隱藏按鈕加入到Grid里
    Button btn = new Button();
    btn.Style = (dictionary["hidenStyle"] as Style);//從樣式文件里讀取到Button的樣式
    btn.Tag = UcListForShow[i].Children;//給Tag賦值,這樣方便查找
    btn.Click += Btn_Click;//註冊隱藏事件
    UcListForShow[i].Children.Add(btn);
}

代碼中,需要註意的是(uc.Parent as Grid).Children.Clear(),如果不移除的話,則會提示,已經屬於另一個,所以,要從parent裡面移除掉。

7、Button的隱藏事件,當Button點擊以後,則要進行隱藏,其實也就是將總數裡面,減除掉不再顯示的那一項

private void Btn_Click(object sender, RoutedEventArgs e)
{
    if ((sender as Button).Tag != null)
    {
        UcListSum.Remove((((sender as Button).Tag as UIElementCollection)[0] as UserControl));
    }
    if (UcListSum.Count == Uc_Count)//當列表數和要展示的數目相同的時候,就停止掉動畫效果
    {
        storyboard_imgs.Completed -= Storyboard_imgs_Completed;
        storyboard_imgs.Stop();
        for (int i = 0; i < Uc_Count; i++)
        {
            UcListForShow[i].Children.Clear();
            if (UcListSum[i].Parent != null)
            {
                (UcListSum[i].Parent as Grid).Children.Clear();
            }
            UcListForShow[i].Children.Add(UcListSum[i]);
        }
        return;
    }
}

所有代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MarqueeUserControl
{
    /// <summary>
    /// MarqueeUC.xaml 的交互邏輯
    /// </summary>
    public partial class MarqueeUC : UserControl
    {
        ResourceDictionary dictionary;
        public MarqueeUC()
        {
            InitializeComponent();
            //讀取樣式文件
            dictionary = new ResourceDictionary { Source = new Uri("/MarqueeUserControl;component/MarqueeUserControlDictionary.xaml", UriKind.Relative) };
        }
        #region 屬性
        private int _uc_Count = 0;
        /// <summary>
        /// 用來展示幾個
        /// </summary>
        public int Uc_Count
        {
            get
            {
                return _uc_Count;
            }

            set
            {
                _uc_Count = value;
            }
        }

        private List<Grid> _ucListForShow = new List<Grid>();
        /// <summary>
        /// 用來展示的控制項列表
        /// </summary>
        private List<Grid> UcListForShow
        {
            get
            {
                return _ucListForShow;
            }

            set
            {
                _ucListForShow = value;
            }
        }

        private List<UserControl> _ucListSum = new List<UserControl>();
        /// <summary>
        /// 要添加的控制項的列表
        /// </summary>
        public List<UserControl> UcListSum
        {
            get
            {
                return _ucListSum;
            }

            set
            {
                _ucListSum = value;
            }
        }

        #endregion
        Canvas canvas_board = new Canvas();
        Storyboard storyboard_imgs = new Storyboard();
        int scroll_index = 0;//滾動索引
        double scroll_width;//滾動寬度

        void GridLayout()
        {
            if (Uc_Count == 0)//如果這個值沒有賦值的話,則預設顯示四個
            {
                Uc_Count = 4;
            }
            //給Canvas設置一些屬性
            canvas_board.VerticalAlignment = VerticalAlignment.Stretch;
            canvas_board.HorizontalAlignment = HorizontalAlignment.Stretch;
            canvas_board.Width = this.viewbox_main.ActualWidth;
            canvas_board.Height = this.viewbox_main.ActualHeight;
            canvas_board.ClipToBounds = true;
            //用viewbox可以支持拉伸
            this.viewbox_main.Child = canvas_board;
            //迴圈將Grid加入到要展示的列表裡
            for (int i = 0; i < Uc_Count + 1; i++)
            {
                Grid grid = new Grid();
                grid.Width = canvas_board.Width / Uc_Count - 10;
                grid.Height = canvas_board.Height - 10;
                grid.Margin = new Thickness(5);
                this.canvas_board.Children.Add(grid);
                grid.SetValue(Canvas.TopProperty, 0.0);
                grid.SetValue(Canvas.LeftProperty, i * (grid.Width + 10));

                UcListForShow.Add(grid);
            }
        }

        void StoryLoad()
        {
            for (int i = 0; i < UcListForShow.Count; i++)
            {//設置滾動時候的效果
                DoubleAnimationUsingKeyFrames daukf_uc = new DoubleAnimationUsingKeyFrames();
                LinearDoubleKeyFrame k1_uc = new LinearDoubleKeyFrame(i * (UcListForShow[i].Width + 10), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)));
                LinearDoubleKeyFrame k2_uc = new LinearDoubleKeyFrame((i - 1) * (UcListForShow[i].Width + 10), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2.5)));
                daukf_uc.KeyFrames.Add(k1_uc);
                daukf_uc.KeyFrames.Add(k2_uc);
                storyboard_imgs.Children.Add(daukf_uc);
                Storyboard.SetTarget(daukf_uc, UcListForShow[i]);
                Storyboard.SetTargetProperty(daukf_uc, new PropertyPath("(Canvas.Left)"));
            }

            storyboard_imgs.FillBehavior = FillBehavior.Stop;
            storyboard_imgs.Completed += Storyboard_imgs_Completed;
            storyboard_imgs.Begin();
        }

        private void Storyboard_imgs_Completed(object sender, EventArgs e)
        {

            scroll_index = scroll_index + 1 - Uc_Count;

            for (int i = 0; i < UcListForShow.Count; i++)
            {
                UcListForShow[i].SetValue(Canvas.LeftProperty, i * (UcListForShow[i].Width + 10));
                UserControl uc;
                if (i == UcListForShow.Count - 1)
                {
                    uc = UcListSum[scroll_index % UcListSum.Count];
                }
                else
                {
                    uc = UcListSum[scroll_index++ % UcListSum.Count];
                }
                if (uc.Parent != null)
                {
                    (uc.Parent as Grid).Children.Clear();//將Usercontrol從原來的裡面移除掉,要不然會拋錯,Usercontrol已屬於另一個控制項
                }
                UcListForShow[i].Children.Clear();
                UcListForShow[i].Children.Add(uc);
                //將隱藏按鈕加入到Grid里
                Button btn = new Button();
                btn.Style = (dictionary["hidenStyle"] as Style);//從樣式文件里讀取到Button的樣式
                btn.Tag = UcListForShow[i].Children;//給Tag賦值,這樣方便查找
                btn.Click += Btn_Click;//註冊隱藏事件
                UcListForShow[i].Children.Add(btn);
            }

            storyboard_imgs.Begin();
        }

        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).Tag != null)
            {
                UcListSum.Remove((((sender as Button).Tag as UIElementCollection)[0] as UserControl));
            }
            if (UcListSum.Count == Uc_Count)//當列表數和要展示的數目相同的時候,就停止掉動畫效果
            {
                storyboard_imgs.Completed -= Storyboard_imgs_Completed;
                storyboard_imgs.Stop();
                for (int i = 0; i < Uc_Count; i++)
                {
                    UcListForShow[i].Children.Clear();
                    if (UcListSum[i].Parent != null)
                    {
                        (UcListSum[i].Parent as Grid).Children.Clear();
                    }
                    UcListForShow[i].Children.Add(UcListSum[i]);
                }
                return;
            }
        }

        public void StartMar()
        {
            GridLayout();

            scroll_width = this.canvas_board.Width;

            for (int i = 0; i < UcListForShow.Count; i++)
            {
                UserControl uc;
                if (i == UcListForShow.Count - 1)
                {
                    uc = UcListSum[scroll_index % UcListSum.Count];
                }
                else
                {
                    uc = UcListSum[scroll_index++ % UcListSum.Count];
                }
                if (uc.Parent != null)
                {
                    (uc.Parent as Grid).Children.Clear();
                }
                UcListForShow[i].Children.Clear();
                UcListForShow[i].Children.Add(uc);
            }
            StoryLoad();
        }

        private void grid_main_MouseLeave(object sender, MouseEventArgs e)
        {
            if (storyboard_imgs.GetCurrentState() == ClockState.Stopped)//如果是停止的狀態,則直接返回,不再起作用
            {
                return;
            }
            if (storyboard_imgs.GetIsPaused() == true)//如果是暫停狀態的話,則開始
            {
                storyboard_imgs.Begin();
            }
        }

        private void grid_main_MouseMove(object sender, MouseEventArgs e)
        {
            if (storyboard_imgs.GetIsPaused() == false)
            {
                storyboard_imgs.Pause();
            }
        }
    }
}
MarqueeUC
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MarqueeUserControl">
    <Style TargetType="Button" x:Key="hidenStyle">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="Width" Value="25"/>
        <Setter Property="Height" Value="25"/>
        <Setter Property="BorderBrush" Value="Transparent"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Template"><!--把Image放到Template里作為Content顯示,如果是單獨給Content設置圖片的話,則只有一個按鈕顯示圖片,其他的不顯示-->
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border>
                        <Image Source="hiden.png"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
MarqueeUserControlDictionary

 

沒有解決的問題

想給Button增加滑鼠懸停的時候,顯示,移除的時候隱藏,但是發現不好使,原因是當MouseOver上去的時候,雖然Visibility的值變了,但是只有到下一次的時候,Button的值才被附上,而此時,已經MouseLeave了,請哪位大神指導一下,看看這個顯示和隱藏怎麼做。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天腦補了普通Windows 操作系統與Windows Server區別,感覺清楚了很多。 Microsoft WindowsServer,是美國微軟公司研製的一套操作體系,它面世於1985年,起先僅僅是Microsoft-DOS模仿環境,後續的體系版別因為微軟不斷的更新晉級,不光易用,也漸漸的變成 ...
  • haproxy記憶體池概述 記憶體池按照類型分類,每個類型的記憶體池都有一個名字,用鏈表記錄空閑的記憶體塊,每個記憶體塊大小相等,並按照16位元組對齊。 haporxy用pool_head 結構記錄記憶體池 在程式執行過程中,產生的記憶體池,很有可能按照大小,排列成如下方式: 記憶體池的創建 haproxy創建記憶體池 ...
  • windows10中的Cortana可以通過語音乾很多事情,但是對於我們來說用處不大,而且開機十分占用記憶體,下麵教大家如何徹底的卸載並刪除: 首先下載卸載Cortana的軟體,下載鏈接:http://pan.baidu.com/s/1cs4Mg2 下載完成後,解壓至本地,打開文件夾》》然後如下圖操作 ...
  • 首先是把 HTML 轉換為圖片。 public partial class Form1 : Form { public Form1() { InitializeComponent(); } WebBrowser webBrowser = null; public void ConvertToImg( ...
  • 1.乾軟體前 在進入軟體這一行之前,我一直從事硬體方面的工作,換過很多個公司,但大體都是做做產品的測試,維護一下產品,工作忙,工資低。年輕人嘛倒不是怕苦怕累,是因為每個工作都學不到自己想學的東西,期間總覺得公司這樣不好,那樣不好。其實現在想來,當初的想法也有一半是錯的,自己都急於求成,缺乏一些忍耐力 ...
  • 端午節剛過,相信大家在端午節都收到不少微信祝福信息,有複製長篇大論的祝福語群發的,有人工手打的簡單祝福群發,我更喜歡人工手打帶上稱呼的祝福信息,這樣看起來更加親切。 那麼問題來了,當你的通訊錄里好友多了,想要送祝福的人多了的時候該咋辦,難道真的一條條去人工手寫嗎?我那麼懶就肯定不會了,我的想法是輔助 ...
  • 今天在研究C#代碼問題的時候遇到了一個Visual Studio的小問題。在Visual Studio 2013中,使用Find All References功能不能找到同一類型不同版本的所有引用,具體情況請見下麵例子。 為了更方便的展示這個問題,我寫了兩段小代碼測試。如下圖,TestFindAll ...
  • var lst = new List<ModelTest>(); lst.Add(new ModelTest() { Code = "1", Name = "一" }); lst.Add(new ModelTest() { Code = "2", Name = "二" }); lst.Add(new ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...