首页 > 解决方案 > 尽管实现了 INotifyPropertyChanged,但 WPF 视图未更新(.NET 5.0)

问题描述

在我看来,我有一个 ProgressBar,它绑定到我的视图模型中的“Progress”属性。viewmodel 实现 INotifyPropertyChanged 并且当属性改变时, OnPropertyChanged() 被调用。

绑定有效,但是视图很少更新 ProgressBar 控件的进度。只有当我用鼠标拖动窗口时,它才会定期更新。

主窗口.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>

主窗口.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));
    }
}

我经常使用 INotifyPropertyChanged 并且通常从来没有遇到过问题,但我在这里看不到问题。

任何建议如何解决这个问题?

标签: c#wpfinotifypropertychanged

解决方案


System.Threading.TimerDispatcherTimer(with )替换DispatcherPriority.Normal解决了这个问题。

谢谢你的建议


推荐阅读