wpf 快速开发框架_用Wpf框架实现图片自动轮播自定义控件源码

时间:2019-11-06  来源:WPF  阅读:

1.创建为自定义控件的XAML页面。

下面为后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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;
using System.Windows.Threading;

namespace EZ.AppPlatform.App.VideoSummary.UserControl
{
    ///


    /// AdvertPicControl.xaml 的交互逻辑
    ///

    public partial class AdvertPicControl : System.Windows.Controls.UserControl
    {
        #region 加载List数据
        ///
        /// 当前图片地址播放列表
        ///

        private static List currentList;

        public static DependencyProperty advertPicList = DependencyProperty.Register("advertPicList", typeof(List), typeof(AdvertPicControl)
            , new PropertyMetadata(new PropertyChangedCallback(loadAdvertPic)));

        public List AdvertPicList
        {
            get { return (List)GetValue(advertPicList); }
            set { SetValue(advertPicList, value); }
        }

        ///
        /// 图片播放器地址
        ///

        ///
        ///
        private static void loadAdvertPic(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            AdvertPicControl advertPicControl = (AdvertPicControl)sender;
            if (e.Property == advertPicList)
            {
                advertPicControl.AdvertPicList = (List)e.NewValue;
                currentList = advertPicControl.AdvertPicList;
            }
        }
        #endregion

        #region 加载图片停留时间
        ///
        /// 当前图片地址播放列表
        ///

        private static List currentTimeList;

        public static DependencyProperty advertPicStayTime = DependencyProperty.Register("advertPicStayTime", typeof(List), typeof(AdvertPicControl)
            , new PropertyMetadata(new PropertyChangedCallback(loadAdvertStayTime)));

        public List AdvertPicStayTime
        {
            get { return (List)GetValue(advertPicStayTime); }
            set { SetValue(advertPicStayTime, value); }
        }

        ///
        /// 图片播放器图片停留时间
        ///

        ///
        ///
        private static void loadAdvertStayTime(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            AdvertPicControl advertPicControl = (AdvertPicControl)sender;
            if (e.Property == advertPicStayTime)
            {
                advertPicControl.AdvertPicStayTime = (List)e.NewValue;
                currentTimeList = advertPicControl.AdvertPicStayTime;
            }
        }
        #endregion

        #region 注册自定义事件和参数
        public static readonly RoutedEvent AdvertPicPlayStateChangedEvent;

        public class AdvertPicPlayEventArgs : RoutedEventArgs
        {
            public int playState
            {
                get;
                set;
            }

            public int playLength
            {
                get;
                set;
            }

            public int playIndex
            {
                get;
                set;
            }
        }

        static AdvertPicControl()
        {
            AdvertPicPlayStateChangedEvent = EventManager.RegisterRoutedEvent("AdvertPicPlayStateChanged",
                RoutingStrategy.Bubble, typeof(AdvertPicPlayStateChangedHandler), typeof(AdvertPicControl));
        }
        public delegate void AdvertPicPlayStateChangedHandler(object sender, AdvertPicPlayEventArgs e);
        public event AdvertPicPlayStateChangedHandler AdvertPicPlayStateChanged
        {
            add { AddHandler(AdvertPicControl.AdvertPicPlayStateChangedEvent, value); }
            remove { RemoveHandler(AdvertPicControl.AdvertPicPlayStateChangedEvent, value); }
        }
        #endregion

        #region 动态加载对应的切换图片按钮,单击响应加载对应的图片。

        #endregion

        public AdvertPicControl()
        {
            InitializeComponent();
        }

        DispatcherTimer switchPicTimer = new DispatcherTimer();
        int i = 0;
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //默认 1秒切换一张图片
           // switchPicTimer.IsEnabled = false;
        
            switchPicTimer.Tick += SwitchPicEvent;
            for (int j = 0; j < currentList.Count; j++)
            {
               Button btn=new Button();
                btn.Width = 20;
                btn.Height = 20;
                btn.Content = j+1;
                btn.Tag = j;
                btn.Click+=new RoutedEventHandler(btn_Click);
                PicCountNum.Children.Add(btn);
            }
         
        }

        void btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button) sender;
            BitmapImage bitmap = new BitmapImage(new Uri(currentList[Convert.ToInt32( btn.Tag)], UriKind.Absolute));
            imgAdvertPic.Stretch = Stretch.Fill;
            imgAdvertPic.Source = bitmap;
        }

        ///
        /// 开始播放
        ///

        /// 图片切换时间
        public void Play(int interval)
        {
            int defaultinterval = 0;
            if (interval != 0)
                defaultinterval = interval;

            switchPicTimer.IsEnabled = true;
            switchPicTimer.Interval = new TimeSpan(0, 0, defaultinterval);
            switchPicTimer.Start();
            i = 0;
        }

        ///
        /// 停止播放
        ///

        public void Stop()
        {
            switchPicTimer.IsEnabled = false;
            switchPicTimer.Stop();
        }

        ///
        /// 切换图片事件
        ///

        ///
        ///
        private void SwitchPicEvent(object sender, EventArgs e)
        {
            if (null != currentList)
            {
               // Console.WriteLine("开始切换~~~");
                if (i <= currentList.Count-1)//修改实现循环播放。
                {
                    DoHandlerStop(Image.OpacityProperty, 20, 0, 4, imgAdvertPic, SwitchPic);
                }
                else
                {
                    //AdvertPicPlayEventArgs args = new AdvertPicPlayEventArgs();
                    //args.RoutedEvent = AdvertPicPlayStateChangedEvent;
                    //args.playState = 1;
                    //RaiseEvent(args);
                    // switchPicTimer.Stop();
                    // switchPicTimer.IsEnabled = false;
                    i = 0;
                    DoHandlerStop(Image.OpacityProperty, 20, 0, 4, imgAdvertPic, SwitchPic);
                 
                }
                if (null != currentTimeList)
                {
                    Thread.Sleep(currentTimeList[i]); //图片停留时间
                }
            }
        }

        ///
        /// 动画播放完毕切换图片
        ///

        ///
        ///
        private void SwitchPic(object sender, EventArgs e)
        {
            BitmapImage bitmap = new BitmapImage(new Uri(currentList[i], UriKind.Absolute));
            imgAdvertPic.Stretch = Stretch.Fill;
            imgAdvertPic.Source = bitmap;
            if (i < currentList.Count)
            {
                i++;
            }
          
        }

        public void ClickToPic(int id)
        {
          
        }


        ///
        /// 动画
        ///

        ///
        ///
        ///
        ///
        ///
        ///
        public void DoHandlerStop(DependencyProperty dp, double from, double to, double duration, UIElement element, EventHandler complateHander)
        {
            DoubleAnimation doubleAnimation = new DoubleAnimation();//创建双精度动画对象
            doubleAnimation.From = from;
            doubleAnimation.To = to;//设置动画的结束值
            doubleAnimation.Duration = TimeSpan.FromSeconds(duration);//设置动画时间线长度
            doubleAnimation.FillBehavior = FillBehavior.Stop;//设置动画完成后执行的操作
            doubleAnimation.Completed += complateHander;
            element.BeginAnimation(dp, doubleAnimation);//设置动画应用的属性并启动动画
        }
    }
}

前台xaml代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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;
using System.Windows.Threading;

namespace EZ.AppPlatform.App.VideoSummary.UserControl
{
    ///
    /// AdvertPicControl.xaml 的交互逻辑
    ///

    public partial class AdvertPicControl : System.Windows.Controls.UserControl
    {
        #region 加载List数据
        ///
        /// 当前图片地址播放列表
        ///

        private static List currentList;

        public static DependencyProperty advertPicList = DependencyProperty.Register("advertPicList", typeof(List), typeof(AdvertPicControl)
            , new PropertyMetadata(new PropertyChangedCallback(loadAdvertPic)));

        public List AdvertPicList
        {
            get { return (List)GetValue(advertPicList); }
            set { SetValue(advertPicList, value); }
        }

        ///
        /// 图片播放器地址
        ///

        ///
        ///
        private static void loadAdvertPic(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            AdvertPicControl advertPicControl = (AdvertPicControl)sender;
            if (e.Property == advertPicList)
            {
                advertPicControl.AdvertPicList = (List)e.NewValue;
                currentList = advertPicControl.AdvertPicList;
            }
        }
        #endregion

        #region 加载图片停留时间
        ///
        /// 当前图片地址播放列表
        ///

        private static List currentTimeList;

        public static DependencyProperty advertPicStayTime = DependencyProperty.Register("advertPicStayTime", typeof(List), typeof(AdvertPicControl)
            , new PropertyMetadata(new PropertyChangedCallback(loadAdvertStayTime)));

        public List AdvertPicStayTime
        {
            get { return (List)GetValue(advertPicStayTime); }
            set { SetValue(advertPicStayTime, value); }
        }

        ///
        /// 图片播放器图片停留时间
        ///

        ///
        ///
        private static void loadAdvertStayTime(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            AdvertPicControl advertPicControl = (AdvertPicControl)sender;
            if (e.Property == advertPicStayTime)
            {
                advertPicControl.AdvertPicStayTime = (List)e.NewValue;
                currentTimeList = advertPicControl.AdvertPicStayTime;
            }
        }
        #endregion

        #region 注册自定义事件和参数
        public static readonly RoutedEvent AdvertPicPlayStateChangedEvent;

        public class AdvertPicPlayEventArgs : RoutedEventArgs
        {
            public int playState
            {
                get;
                set;
            }

            public int playLength
            {
                get;
                set;
            }

            public int playIndex
            {
                get;
                set;
            }
        }

        static AdvertPicControl()
        {
            AdvertPicPlayStateChangedEvent = EventManager.RegisterRoutedEvent("AdvertPicPlayStateChanged",
                RoutingStrategy.Bubble, typeof(AdvertPicPlayStateChangedHandler), typeof(AdvertPicControl));
        }
        public delegate void AdvertPicPlayStateChangedHandler(object sender, AdvertPicPlayEventArgs e);
        public event AdvertPicPlayStateChangedHandler AdvertPicPlayStateChanged
        {
            add { AddHandler(AdvertPicControl.AdvertPicPlayStateChangedEvent, value); }
            remove { RemoveHandler(AdvertPicControl.AdvertPicPlayStateChangedEvent, value); }
        }
        #endregion

        #region 动态加载对应的切换图片按钮,单击响应加载对应的图片。

        #endregion

        public AdvertPicControl()
        {
            InitializeComponent();
        }

        DispatcherTimer switchPicTimer = new DispatcherTimer();
        int i = 0;
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //默认 1秒切换一张图片
           // switchPicTimer.IsEnabled = false;
        
            switchPicTimer.Tick += SwitchPicEvent;
            for (int j = 0; j < currentList.Count; j++)
            {
               Button btn=new Button();
                btn.Width = 20;
                btn.Height = 20;
                btn.Content = j+1;
                btn.Tag = j;
                btn.Click+=new RoutedEventHandler(btn_Click);
                PicCountNum.Children.Add(btn);
            }
         
        }

        void btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button) sender;
            BitmapImage bitmap = new BitmapImage(new Uri(currentList[Convert.ToInt32( btn.Tag)], UriKind.Absolute));
            imgAdvertPic.Stretch = Stretch.Fill;
            imgAdvertPic.Source = bitmap;
        }

        ///
        /// 开始播放
        ///

        /// 图片切换时间
        public void Play(int interval)
        {
            int defaultinterval = 0;
            if (interval != 0)
                defaultinterval = interval;

            switchPicTimer.IsEnabled = true;
            switchPicTimer.Interval = new TimeSpan(0, 0, defaultinterval);
            switchPicTimer.Start();
            i = 0;
        }

        ///
        /// 停止播放
        ///

        public void Stop()
        {
            switchPicTimer.IsEnabled = false;
            switchPicTimer.Stop();
        }

        ///
        /// 切换图片事件
        ///

        ///
        ///
        private void SwitchPicEvent(object sender, EventArgs e)
        {
            if (null != currentList)
            {
               // Console.WriteLine("开始切换~~~");
                if (i <= currentList.Count-1)//修改实现循环播放。
                {
                    DoHandlerStop(Image.OpacityProperty, 20, 0, 4, imgAdvertPic, SwitchPic);
                }
                else
                {
                    //AdvertPicPlayEventArgs args = new AdvertPicPlayEventArgs();
                    //args.RoutedEvent = AdvertPicPlayStateChangedEvent;
                    //args.playState = 1;
                    //RaiseEvent(args);
                    // switchPicTimer.Stop();
                    // switchPicTimer.IsEnabled = false;
                    i = 0;
                    DoHandlerStop(Image.OpacityProperty, 20, 0, 4, imgAdvertPic, SwitchPic);
                 
                }
                if (null != currentTimeList)
                {
                    Thread.Sleep(currentTimeList[i]); //图片停留时间
                }
            }
        }

        ///
        /// 动画播放完毕切换图片
        ///

        ///
        ///
        private void SwitchPic(object sender, EventArgs e)
        {
            BitmapImage bitmap = new BitmapImage(new Uri(currentList[i], UriKind.Absolute));
            imgAdvertPic.Stretch = Stretch.Fill;
            imgAdvertPic.Source = bitmap;
            if (i < currentList.Count)
            {
                i++;
            }
          
        }

        public void ClickToPic(int id)
        {
          
        }


        ///
        /// 动画
        ///

        ///
        ///
        ///
        ///
        ///
        ///
        public void DoHandlerStop(DependencyProperty dp, double from, double to, double duration, UIElement element, EventHandler complateHander)
        {
            DoubleAnimation doubleAnimation = new DoubleAnimation();//创建双精度动画对象
            doubleAnimation.From = from;
            doubleAnimation.To = to;//设置动画的结束值
            doubleAnimation.Duration = TimeSpan.FromSeconds(duration);//设置动画时间线长度
            doubleAnimation.FillBehavior = FillBehavior.Stop;//设置动画完成后执行的操作
            doubleAnimation.Completed += complateHander;
            element.BeginAnimation(dp, doubleAnimation);//设置动画应用的属性并启动动画
        }
    }
}

2.创建主窗体:

调用部分:

xaml部分,一个grid控件

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TestPicscroll" Height="340" Width="594" Loaded="Window_Loaded">
   
       
   
   



服务端代码部分。

using System;
using System.Collections.Generic;
using System.IO;
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.Imaging;
using System.Windows.Shapes;
using EZ.AppPlatform.App.VideoSummary.UserControl;

namespace EZ.AppPlatform.App.VideoSummary
{
    ///
    /// TestPicscroll.xaml 的交互逻辑
    ///

    public partial class TestPicscroll : Window
    {
        public TestPicscroll()
        {
            InitializeComponent();
        }
        ///
        /// 获取当前用户的图片文件夹中的图片(不包含子文件夹)
        ///

        /// 返回图片路径列表
        private List GetUserImages(string path)
        {
            List images = new List();
           //Environment.GetFolderPath();//Environment.SpecialFolder.MyPictures
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] files = GetPicFiles(path, "*.jpg,*.png,*.bmp,*.gif,", SearchOption.TopDirectoryOnly);// dir.GetFiles("*.jpg", SearchOption.AllDirectories);

            if (files != null)
            {
                foreach (FileInfo file in files)
                {
                    images.Add(file.FullName);
                }
            }
            return images;
        }

        public FileInfo[] GetPicFiles(string picPath, string searchPattern, SearchOption searchOption)
        {
            System.Collections.Generic.List ltList = new List();
            DirectoryInfo dir = new DirectoryInfo(picPath);
            string[] sPattern = searchPattern.Replace(';', ',').Split(',');
            for (int i = 0; i < sPattern.Length; i++)
            {
                FileInfo[] files = null;
                try
                {
                    files = dir.GetFiles(sPattern[i], searchOption);
                }
                catch (System.Exception ex)
                {
                    files = new FileInfo[] { };
                }

                ltList.AddRange(files);
            }
            return ltList.ToArray();
        }
        AdvertPicControl advertPic = new AdvertPicControl();
        string path = @"E:\ProjectSource\AppDesk\EZ.AppPlatform.App.VideoSummary\Assets\Images\tem";
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            List imageList = GetUserImages(path);
            advertPic.AdvertPicList = imageList;// this.GetUserImages();
            grdContent.Children.Add(advertPic);
            advertPic.AdvertPicPlayStateChanged += playStateHandler;
           advertPic.Play(2);
        }


        private void playStateHandler(object sender, AdvertPicControl.AdvertPicPlayEventArgs args)
        {
           // MessageBox.Show("播放完了,触发事件....");
            advertPic.Stop();
           advertPic.Play(2);
        }

      /////
      ///// 开始播放
      /////

      /////
      /////
      //  private void button1_Click(object sender, RoutedEventArgs e)
      //  {
      //      advertPic.Play(Convert.ToInt32(2)); //设置默认切换时间
      //  }
      //  ///
      //  /// 停止播放
      //  ///

      //  ///
      //  ///
      //  private void button2_Click(object sender, RoutedEventArgs e)
      //  {
      //      advertPic.Stop();
      //  }
    }
}

然后设置app.xaml启动项为主窗体,然后运行,默认为2s切换一次。

wpf 快速开发框架_用Wpf框架实现图片自动轮播自定义控件源码

http://m.bbyears.com/asp/77699.html

推荐访问:wpf mvvm框架
相关阅读 猜你喜欢
本类排行 本类最新