wpf——自定义进度条控件

首先在自定义控件里添加进度条。


        
            
            
            
        
    

然后在后台添加点击的路由事件,并把该事件在cancle_Click中释放。

 public partial class ProgressBarControl : UserControl
    {
        public ProgressBarControl()
        {
            InitializeComponent();
        }

        public static readonly RoutedEvent CancleClickEvent =
            EventManager.RegisterRoutedEvent("CancleClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ProgressBarControl));

        public event RoutedEventHandler CancleClick
        {
            add
            {
                this.AddHandler(CancleClickEvent, value);
            }

            remove
            {
                this.RemoveHandler(CancleClickEvent, value);
            }
        }

        private void cancle_Click(object sender, RoutedEventArgs e)
        {
            RoutedEventArgs args = new RoutedEventArgs(CancleClickEvent, this);
            this.RaiseEvent(args);
        }
    }

然后定义一个类,存放进度条数据。

public class ProgressBarModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        private int progressValue;

        public int ProgressValue
        {
            get
            {
                return progressValue;
            }

            set
            {
                progressValue = value; NotifyPropertyChanged("ProgressValue");
            }
        }
        private string progressInfo;

        public string ProgressInfo
        {
            get
            {
                return progressInfo;
            }

            set
            {
                progressInfo = value; NotifyPropertyChanged("ProgressInfo");
            }
        }       
    }

接着在主窗口中用上这个自定义进度条控件。


    
        
    

最后在后台写进度条改变的方法。

public partial class MainWindow : Window
    {
        CommonControls.ProgressBarModel _model;
        public MainWindow()
        {
            InitializeComponent();
            CommonControls.ProgressBarModel model = new CommonControls.ProgressBarModel();
            _model = model;
            this.DataContext = _model;
        }

        private void cancle_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(() => {
                for(int i=0;i<101;i++)
                {
                    _model.ProgressValue = i;
                    _model.ProgressInfo = i.ToString() + "%";
                    Thread.Sleep(50);
                }
            });
            thread.Start();
        }
    }

最终的结果:

wpf——自定义进度条控件_第1张图片

这里的难点是在自定义控件里添加路由事件,然后进度条在新线程中运行。

你可能感兴趣的:(wpf)