"忙碌"效果叠加

Mat*_*arr 9 wpf

我有一个wpf应用程序,它执行非常繁重的操作,用户需要在应用程序"思考"时等待.

我想要做的是,当应用程序的主线程思考时,另一个线程将禁用整个窗口并给它一种浅灰色,并在屏幕中间出现一个圆形进度条.

这是一个很大的问题,我真的不需要整个代码来做这个只是一般的想法.

感谢你的帮助..

Dr.*_*ABT 12

除了上面的建议(后台工作者,调度员) - 是的,这些是获得你想要的正确技巧,但让我讨论你在问题中要求的UI效果.如果您正在使用MVVM模式,则可以创建一些"我很忙"UI并绑定到视图模型中的IsBusy属性以显示和隐藏UI.例如:

public class MyViewModel : INotifyPropertyChanged
{
    // Bind to this property any UI you want to 
    // show/hide during long running updates
    public bool IsBusy 
    { 
        get { return _isBusy; } 
        set 
        {
            _isBusy = true; 
            OnPropertyChanged("IsBusy");
        }
    } 

    private void OnPropertyChanged(string prop)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(prop));
        }
    }

    // Note: This is intended to be called on a background thread
    private void DoLongRunningOperationOnABackgroundThread()
    {
        try
        {
            IsBusy = true;

            // do your work
        }
        finally
        {
            IsBusy = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在UI中使用此xaml(或类似)

<UserControl:MyControl x:Class="MyApp.MyControl"
                          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="boolToVis"/>
    </UserControl.Resources>
    <Grid>
        <!-- your UI code goes here -->

        <!-- Below this, at higher Z-Order place a control to gray out the screen when IsBusy = true -->
        <Border Background="#55000000" BorderThickness="0" Visibility="{Binding IsBusy, Converter={StaticResource boolToVis}}">
            <TextBlock Text="I AM BUSY!" Font-Size="32" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="White"/>
        </Border>
    <Grid>
</UserControl>    
Run Code Online (Sandbox Code Playgroud)

当您使用后台工作程序或线程池在视图模型中调用DoLongRunningOperation函数时,将产生净效果,Xaml中定义的边框将在操作开始/停止时显示/隐藏.您不需要调度程序在此处调用,因为WPF会为您处理线程编组.

在网上也有繁忙的控件和whirlygig动画等的实现,以增加UI的功能.

最好的祝福,


Lar*_*ens 2

将繁重的操作卸载到新线程,并在主线程上执行 UI 操作(禁用、变灰和进度条)。请参阅BackgroundWorker 和Dispatcher

可以为 UI 内容使用新线程,但不能使用现有窗口。UI 控件(Dispatcher)可以由它所属的线程在线使用/调用。但是,您可以创建一个新线程并使用带有新调度程序的新窗口来执行 UI 操作。然后,您必须将新窗口放置在原始窗口之上。不像我的第一个建议那么容易。如果您不知道何时执行繁重的操作,这可能是一个选择。请参阅此处此处此处