接下来,我们采用绑定的方式来实现进度条的显示
首先新建一个Progress类
class Progress : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double _minimum;
/// <summary>
/// 最小值
/// </summary>
public double Minimum
{
get { return this._minimum; }
set
{
this._minimum = value;
RaisePropertyChanged("Minimum");
}
}
private double _maximum = 100;
/// <summary>
/// 最大值
/// </summary>
public double Maximum
{
get { return this._maximum; }
set
{
this._maximum = value;
RaisePropertyChanged("Maximum");
}
}
private double _value;
/// <summary>
/// 当前数值
/// </summary>
public double Value
{
get { return _value; }
set
{
this._value = value;
RaisePropertyChanged("Value");
}
}
private string _text;
/// <summary>
/// 当前数值
/// </summary>
public string Text
{
get { return _text; }
set
{
this._text = value;
RaisePropertyChanged("Text");
}
}
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<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" Click="Button_Click_1"></Button>
</StackPanel>
</Window>
namespace MVVM3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Progress();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Progress progress = this.DataContext as Progress;
Thread thread = new Thread(new ThreadStart(() =>
{
for (int i = 1; i <= 100; i++)
{
progress.Value = i;
progress.Text = string.Format("{0}%", i);
Thread.Sleep(200);
}
}));
thread.Start();
}
}
}