c# - 尽管实现了 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 并且通常从来没有遇到过问题,但我在这里看不到问题。
任何建议如何解决这个问题?
解决方案
System.Threading.Timer
用DispatcherTimer
(with )替换DispatcherPriority.Normal
解决了这个问题。
谢谢你的建议
推荐阅读
- php - 通过 PHP 从端点返回“null”
- node.js - 如何使用 graphql 和 mongoose 进行突变
- r - 如何将标签添加到多个 ggplot 图(A、B、C)
- elasticsearch - 如何在 kafka-connect 融合平台的 elasticsearch sink 连接器配置中使用 ca cert?
- apache-spark - 编写数据帧时从 Spark 到数据库的连接有多少?
- python - 用户输入问题
- visual-studio-code - 在VScode中,如何在launch.json中添加带有$的参数
- pyodbc - 如何使用 pyodbc 接口连接计算表
- vue.js - 带有 Vue 的 Apache ECharts 不显示工具提示
- html - 我的 CSS 无法识别滚动捕捉命令