在视图加载WPF MVVM后执行命令

Ofi*_*fir 18 wpf triggers command mvvm

我有一个基于项目的WPF和MVVM.我的项目基于一个包含内容控件的向导,该控件显示我的视图(用户控件)我想在完全加载视图后执行命令,我希望用户在执行命令后立即查看视图UI.

我试过用:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding StartProgressCommand}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
Run Code Online (Sandbox Code Playgroud)

但是在我看到视图UI之前执行该命令并且它不是我正在寻找的.

有谁知道我应该如何实现它?

Lou*_*ann 16

这是因为即使技术上加载了视图(即:所有组件都已在内存中准备好),您的应用程序还没有空闲,因此UI尚未刷新.

Loaded事件上使用交互触发器设置命令已经很好了,因为没有更好的事件要附加到.
现在要等到显示用户界面,在你的StartProgress()(我假设这是StartProgressCommand指向的方法的名称)中这样做:

public void StartProgress()
{
    new DispatcherTimer(//It will not wait after the application is idle.
                       TimeSpan.Zero,
                       //It will wait until the application is idle
                       DispatcherPriority.ApplicationIdle, 
                       //It will call this when the app is idle
                       dispatcherTimer_Tick, 
                       //On the UI thread
                       Application.Current.Dispatcher); 
}

private static void dispatcherTimer_Tick(object sender, EventArgs e)
{
    //Now the UI is really shown, do your computations
}
Run Code Online (Sandbox Code Playgroud)

  • 老我知道但是对于那些匆忙的人来说这是如何结束线程:在你的事件处理程序var timer = sender as DispatcherTimer; timer.Stop(); (3认同)

Ste*_*tes 13

您可以为此使用Dispatcher并将优先级设置为ApplicationIdle,以便在所有内容完成时执行

            Application.Current.Dispatcher.Invoke(
            DispatcherPriority.ApplicationIdle,
            new Action(() =>
            {
               StartProgressCommand.Invoke(args);

            }));
Run Code Online (Sandbox Code Playgroud)

有关调度程序的更多信息,请访问http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherpriority.aspx

干杯.STE.

  • Invoke似乎对我没有帮助,所以我用BeginInvoke代替了Invoke。效果很好。 (2认同)