等待事件时,WPF GUI未在加载时更新

本文关键字:加载 更新 WPF 事件 等待 GUI | 更新日期: 2023-09-27 18:19:34

在我的应用程序中,我有一个view,它以以下方式打开:

ManagerView view = new ManagerView();
view.ShowDialog();

这是View:

<Window x:Class="WpfUpdateGui.ManagerView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:WpfUpdateGui">
<Window.DataContext>
    <local:ManagerViewModel />
</Window.DataContext>
<i:Interaction.Triggers>
    <i:EventTrigger EventName="ContentRendered">
        <i:InvokeCommandAction Command="{Binding LoadedCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
<TextBox Text="{Binding Messages}" />

和我的ViewModel:

public class ManagerViewModel : INotifyPropertyChanged
{
    /*INPC Members...*/
    private string _messages;
    private static EventWaitHandle _timerWaiter;
    /*Constructor*/
    public ManagerViewModel()
    {
        _timerWaiter = new EventWaitHandle(false, EventResetMode.AutoReset);
        LoadedCommand = new RelayCommand(StartProcess);
    }
    private void StartProcess()
    {
        Application.Current.Dispatcher.Invoke(
            DispatcherPriority.ApplicationIdle,
            new Action(() =>
            {
                AddMessage("Starting");
                Worker worker = new Worker();
                worker.DidSomethingEvent += Worker_DidSomethingEvent;
                worker.DoSomeThing();
                _timerWaiter.WaitOne();
                AddMessage("Finished");
            }));
    }
    private void AddMessage(string message)
    {
        Application.Current.Dispatcher.Invoke(() => Messages += $"'r'n{message}");
    }
    private void Worker_DidSomethingEvent()
    {
        _timerWaiter.Set();
    }
    public RelayCommand LoadedCommand { get; set; }
    public string Messages
    {
        get { return _messages; }
        set
        {
            if (value == Messages) return;
            _messages = value;
            OnPropertyChanged("Messages");
        }
    }
}
public class Worker
{
    public event Action DidSomethingEvent;
    public void DoSomeThing()
    {
        Thread.Sleep(2500);
        DidSomethingEvent();
    }
}

我的问题是,我要显示的第一条消息("Starting")只有在设置了EventWaitHandle之后才会显示,甚至在WaitOne()调用之前添加了它。

等待事件时,WPF GUI未在加载时更新

只需将ContentRendered替换为Loaded事件,它就可以工作了。(它确实对我有用)。