问题
I am going through the tutorials on how to implement INotifyPropertyChanged for a progressbar and I think i am a bit confused.
This is my XAML code snippet:
<ProgressBar Name="progressBar" Height="24" IsIndeterminate="{Binding IsIndeterminate}" Minimum="{Binding Minimum}" Maximum="{Binding Maximum}" Value="{Binding ProgressValue}"/>
and this is my code-behind snippet:
public partial class MainWindow : System.Windows.Window {
public bool IsInderteminate { get; set; }
public double Minimum { get; set; }
public double Maximum { get; set; }
public double ProgressValue { get; set; }
public MainWindow() {
InitializeComponent();
this.progressBar.DataContext = this;
this.IsInderteminate = false;
}
private void btnLoadPremiumDetail_Click(object sender, RoutedEventArgs e) {
this.IsInderteminate = true;
// I do my work here
this.IsInderteminate = false;
}
private void _ValidateProcurementDetail() {
for (int i = 0; i < rowCount; i++) {
this.ProgressValue += 1;
//I do work here
}
}
}
How do i implement the INotifyPropertyChanged so that my progressBar gets updated everytime I set the ProgressValue or IsIndeterminate?
回答1:
here how to do it:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.progressBar.DataContext = this;
this.IsInderteminate = false;
}
private bool _isInderteminate = false;
public bool IsInderteminate
{
get { return _isInderteminate; }
set
{
if (_isInderteminate == value)
{
return;
}
_isInderteminate = value;
OnPropertyChanged();
}
}
private double _minimum;
public double Minimum
{
get { return _minimum; }
set
{
if (_minimum == value)
{
return;
}
_minimum = value;
OnPropertyChanged();
}
}
private double _maximum;
public double Maximum
{
get { return _maximum; }
set
{
if (_maximum == value)
{
return;
}
_maximum = value;
OnPropertyChanged();
}
}
private double _progressValue;
public double ProgressValue
{
get { return _progressValue; }
set
{
if (_progressValue == value)
{
return;
}
_progressValue = value;
OnPropertyChanged();
}
}
private void btnLoadPremiumDetail_Click(object sender, RoutedEventArgs e)
{
this.IsInderteminate = true;
// I do my work here
this.IsInderteminate = false;
}
private void _ValidateProcurementDetail()
{
for (int i = 0; i < rowCount; i++)
{
this.ProgressValue += 1;
//I do work here
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
in the Xaml add the Binding Mode=TwoWay, you could also set the DataContext Directly from the Xaml so you can get IntelliSense like so:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
来源:https://stackoverflow.com/questions/27524706/how-to-implement-inotifypropertychanged-for-wpf-progressbar