Widok WPF nie jest aktualizowany, chociaż zaimplementowano INotifyPropertyChanged (.NET 5.0) [duplikat]

Jan 05 2021

Moim zdaniem mam ProgressBar, który jest powiązany z właściwością „Progress” w moim modelu widoku. Viewmodel implementuje INotifyPropertyChanged, a gdy właściwość zostanie zmieniona, wywoływana jest OnPropertyChanged ().

Powiązanie działa, jednak widok rzadko aktualizuje postęp kontrolki ProgressBar. Aktualizuje się regularnie tylko wtedy, gdy przeciągam okno myszą.

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));
    }
}

Często używałem INotifyPropertyChanged i zwykle nigdy nie mam z tym problemów, ale nie widzę tutaj problemu.

Jakieś sugestie, jak rozwiązać ten problem?

Odpowiedzi

2 soaringmatty Jan 05 2021 at 21:26

Wymiana System.Threading.Timerz DispatcherTimer(z DispatcherPriority.Normal) rozwiązało problemu.

Dziękuję za sugestie