In my view I have a ProgressBar which binds to a "Progress" property in my viewmodel. The viewmodel implements INotifyPropertyChanged and when the property is changed, OnPropertyChanged() is called.
The binding works however the view rarely updates the progress of the ProgressBar control. It only regularly updates when I am draging the window around with the mouse.
MainWindow.xaml
<Window
x:Class="WpfTest.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:local="clr-namespace:WpfTest"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="500"
Height="500"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d">
<Grid>
<ProgressBar Value="{Binding Progress}"/>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
}
MainWindowViewModel.cs
class MainWindowViewModel : INotifyPropertyChanged
{
private readonly Timer updateProgressBarTimer;
private int progress;
public int Progress
{
get => progress;
set
{
this.progress = value;
OnPropertyChanged();
}
}
public MainWindowViewModel()
{
updateProgressBarTimer = new Timer(OnUpdateProgressBarTimerTick, null, 0, 50);
}
private void OnUpdateProgressBarTimerTick(object state)
{
this.Progress += 2;
if (this.Progress > 100)
this.Progress -= 100;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
I have used INotifyPropertyChanged a lot and usually never have issues with it but I can't see the problem here.
Any suggestions how to fix this issue?