WPF MVVM 不更新视图

问题描述 投票:0回答:1

我正在开发一个需要秒表的应用程序。我想使用文本块显示经过的时间。我的问题是,视图没有更新,但我可以使用 ICommands。

这里我指定了

DataContext

public partial class ProgressPage : Grid
{
    public ProgressPage(ProjectInfo projectInfo)
    {
        DataContext = new ProgressViewModel(projectInfo);
        InitializeComponent();
    }
}

这是我的

ViewModel

public class ProgressViewModel : INotifyPropertyChanged
{
    private ProjectInfo projectInfo;
    private ICommand _start;
    private DispatcherTimer timer = new()
    {
        Interval = TimeSpan.FromSeconds(1)
    };

    public event PropertyChangedEventHandler? PropertyChanged;

    public ProjectInfo ProjectInfo
    {
        get { return projectInfo; }
        set
        {
            projectInfo = value;
            NotifyPropertyChanged();
        }
    }

    private string elapsedTimeString;

    public string ElapsedTimeString
    {
        get { return elapsedTimeString; }
        set
        {
            elapsedTimeString = value;
            NotifyPropertyChanged();
        }
    }

    public ICommand StartCommand
    {
        get
        {
            _start ??= new RelayCommand(
                    p => true,
                    p => Start());
            return _start;
        }
    }

    private void Start()
    {
        ProjectInfo.CurrentStartedTime = DateTime.Now;
        timer.Start();
    }

    public ProgressViewModel(ProjectInfo projectInfo)
    {
        ProjectInfo = projectInfo;
        timer.Tick += Tick;
    }

    private void Tick(object? sender, EventArgs e)
    {
        ElapsedTimeString = (DateTime.Now - ProjectInfo.CurrentStartedTime).ToString(@"hh\:mm\:ss");
    }

    private void NotifyPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(null, new PropertyChangedEventArgs(name));
    }
}

这是我的

XAML

<TextBlock Text="{Binding ElapsedTimeString}"
           Style="{StaticResource ProgressText}" />

这是一张图片,断点被捕获 break point caught

命令正在工作,计时器正在工作,

NotifyPropertyChanged
方法也正在工作(名称参数也正确),但视图没有更新。

我该如何解决这个问题?

c# wpf mvvm binding viewmodel
1个回答
0
投票

也许尝试添加

<TextBlock Text="{Binding ElapsedTimeString, UpdateSourceTrigger=PropertyChanged}"
           Style="{StaticResource ProgressText}" />
© www.soinside.com 2019 - 2024. All rights reserved.