La vue WPF ne se met pas à jour bien que INotifyPropertyChanged soit implémenté (.NET 5.0) [duplicate]
À mon avis, j'ai un ProgressBar qui se lie à une propriété "Progress" dans mon viewmodel. Le viewmodel implémente INotifyPropertyChanged et lorsque la propriété est modifiée, OnPropertyChanged () est appelé.
La liaison fonctionne mais la vue met rarement à jour la progression du contrôle ProgressBar. Il ne se met à jour régulièrement que lorsque je fais glisser la fenêtre avec la souris.
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));
}
}
J'ai beaucoup utilisé INotifyPropertyChanged et je n'ai généralement jamais de problèmes avec, mais je ne vois pas le problème ici.
Des suggestions pour résoudre ce problème?
Réponses
Le remplacement du System.Threading.Timer
par un DispatcherTimer
(avec DispatcherPriority.Normal
) a résolu le problème.
Merci pour vos suggestions