然后我们采用MVVM来实现进度条的进度显示
首先是Model模块的代码:
class Progress
{
public double Minimum { get; set; }
public double Maximum { get; set; }
public double Value { get; set; }
public string Text { get; set; }
}
接着是Command模块的代码:
class DelayCommand : ICommand
{
private Action _action;
public DelayCommand(Action action)
{
this._action = action;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this._action();
}
}
然后是ViewModel模块的代码:
namespace MVVM3
{
class ProgressViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Progress Progress { get; set; }
/// <summary>
/// 最小值
/// </summary>
public double Minimum
{
get { return this.Progress.Minimum; }
set
{
this.Progress.Minimum = value;
RaisePropertyChanged("Minimum");
}
}
/// <summary>
/// 最大值
/// </summary>
public double Maximum
{
get { return this.Progress.Maximum; }
set
{
this.Progress.Maximum = value;
RaisePropertyChanged("Maximum");
}
}
/// <summary>
/// 当前数值
/// </summary>
public double Value
{
get { return this.Progress.Value; }
set
{
this.Progress.Value = value;
RaisePropertyChanged("Value");
}
}
/// <summary>
/// 当前数值
/// </summary>
public string Text
{
get { return this.Progress.Text; }
set
{
this.Progress.Text = value;
RaisePropertyChanged("Text");
}
}
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public DelayCommand Command { get; set; }
public ProgressViewModel()
{
this.Progress = new Progress() { Maximum = 100 };
this.Command = new DelayCommand(PrintProgress);
}
private void PrintProgress()
{
Thread thread = new Thread(new ThreadStart(() =>
{
for (int i = 1; i <= 100; i++)
{
this.Value = i;
this.Text = string.Format("{0}%", i);
Thread.Sleep(200);
}
}));
thread.Start();
}
}
}
最后是View模块的代码:
<Window x:Class="MVVM3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock x:Name="tb" Height="23" Text="{Binding Text}"></TextBlock>
<ProgressBar x:Name="pb" Height="20" Minimum="{Binding Minimum}" Maximum="{Binding Maximum}" Value="{Binding Value}"></ProgressBar>
<Button Content="click" Width="72" Height="23" Command="{Binding Command}"></Button>
</StackPanel>
</Window>
当然,还要绑定数据上下文:
namespace MVVM3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ProgressViewModel();
}
}
}