首先在自定义控件里添加进度条。
<Grid> <StackPanel HorizontalAlignment="Center" Orientation="Horizontal"> <TextBlock Text="{Binding Path=ProgressInfo}"></TextBlock> <ProgressBar Minimum="0" Maximum="100" Value="{Binding Path=ProgressValue}" Width="200" Height="10"></ProgressBar> <Button Click="cancle_Click" Height="20" Margin="10">Cancle</Button> </StackPanel> </Grid>
然后在后台添加点击的路由事件,并把该事件在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"); } } }
接着在主窗口中用上这个自定义进度条控件。
<Window x:Class="事件Test0402002.MainWindow" 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" xmlns:local="clr-namespace:事件Test0402002" xmlns:lib="clr-namespace:事件Test0402002.CommonControls" mc:Ignorable="d" Loaded="window_Loaded" Title="MainWindow" Height="80" Width="300"> <Grid> <lib:ProgressBarControl CancleClick="cancle_Click"></lib:ProgressBarControl> </Grid> </Window>
最后在后台写进度条改变的方法。
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(); } }
最终的结果:
这里的难点是在自定义控件里添加路由事件,然后进度条在新线程中运行。