c# - 使用 InteractionRequests 设计一个 "busy"对话框

标签 c# mvvm prism prism-4 interaction

我目前正在使用 Prism 的 InteractionRequest 来显示新窗口。在 sample here 之后,我将它们用于简单的确认以及显示带有自定义 View / View 模型的窗口窗口。 .不管怎样,在所有这些情况下,我都会显示窗口,窗口上的一些按钮负责关闭它。我想显示一个窗口并让调用它的对象负责关闭它。

这是我的实现:

Action 通知

public abstract class ActionNotification: Notification, INotifyPropertyChanged, IPopupWindowActionAware
{
    public event PropertyChangedEventHandler PropertyChanged;

    // IPopupWindowActionAware 
    public System.Windows.Window HostWindow { get; set; } // Set when the "action" in the view is triggered
    public Notification HostNotification { get; set; } // Set when the "action" in the view is triggered

    public ActionNotification(string content)
    {
        this.Content = content;
    }

    public void CompleteAction()
    {
        if (this.HostWindow != null)
        {
            this.HostWindow.Close();
        }
    }

    // INotifyPropertyChange implementation
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

调用方式

/// <summary>
/// Pushes a unit of work onto a separate thread and notifies the view to display an action notification
/// </summary>
/// <param name="actionNotification">The notification object for the view to display</param>
/// <param name="act">The unit of work to perform on a separate thread</param>
private void DoWorkAndRaiseAction(ActionNotification actionNotification, Action act)
{
    Task.Factory.StartNew(() =>
    {
        try
        {
            act();
        }
        finally
        {
            Application.Current.Dispatcher.Invoke((Action)(() => actionNotification.CompleteAction()));
        }
    });

    ActionInteractionReq.Raise(actionNotification);
}

这一切都很好,但如果在我能够引发 InteractionRequest 之前完成“工作”,我似乎会很糟糕。任何人都可以向 GUARANTEE 提供一些建议,要么在提出请求之前工作尚未完成,要么不要突袭该请求?

编辑:我应该补充一点,窗口显示为模式,因此在提出请求后不会执行任何代码,这就是为什么我将工作推到一个单独的任务

EDIT2:下面是 View 与请求交互的方式:

<i:Interaction.Triggers>
    <prism:InteractionRequestTrigger SourceObject="{Binding Path=ActionInteractionReq, Mode=OneWay}">
        <int_req:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True" WindowStyle="None" WindowHeight="150" WindowWidth="520">
            <int_req:PopupWindowAction.WindowContent>
                <int_req:ZActionNotificationView/>
            </int_req:PopupWindowAction.WindowContent>
        </int_req:PopupWindowAction>
    </prism:InteractionRequestTrigger>
</i:Interaction.Triggers>

调用 Raise 时,将触发 PopupWindowAction 并创建一个新窗口。然后在该窗口上执行 ShowDialog

EDIT3: 根据评论的建议,我已经包含了 PopupWindowAction。为了简洁起见,我删掉了一些不相关的代码

public class PopupWindowAction : TriggerAction<FrameworkElement>
{
    /*      
       Here is where a few dependency properties live that dictate things like Window size and other stuff, e.g.

        /// <summary>
        /// Determines if the content should be shown in a modal window or not.
        /// </summary>
        public static readonly DependencyProperty IsModalProperty =
            DependencyProperty.Register(
                "IsModal",
                typeof(bool),
                typeof(PopupWindowAction),
                new PropertyMetadata(null));        
    */

    /* 
        Here is where the accessors live for the DPs, e.g.

        /// <summary>
        /// Gets or sets if the window will be modal or not.
        /// </summary>
        public bool IsModal
        {
            get { return (bool)GetValue(IsModalProperty); }
            set { SetValue(IsModalProperty, value); }
        }
    */

    #region PopupWindowAction logic

    /// <summary>
    /// Displays the child window and collects results for <see cref="IInteractionRequest"/>.
    /// </summary>
    /// <param name="parameter">The parameter to the action. If the action does not require a parameter, the parameter may be set to a null reference.</param>
    protected override void Invoke(object parameter)
    {
        var args = parameter as InteractionRequestedEventArgs;
        if (args == null)
        {
            return;
        }

        // If the WindowContent shouldn't be part of another visual tree.
        if (this.WindowContent != null && this.WindowContent.Parent != null)
        {
            return;
        }

        var wrapperWindow = this.GetWindow(args.Context); // args.Context here is the Notification object I'm passing to the InteractionRequest

        var callback = args.Callback;
        EventHandler handler = null;
        handler =
            (o, e) =>
            {
                wrapperWindow.Closed -= handler;
                wrapperWindow.Owner = null;
                wrapperWindow.Content = null;
                callback();
            };
        wrapperWindow.Closed += handler;

        if (this.IsModal)
        {
            wrapperWindow.ShowDialog();
        }
        else
        {
            wrapperWindow.Show();
        }
    }

    /// <summary>
    /// Checks if the WindowContent or its DataContext implements IPopupWindowActionAware and IRegionManagerAware.
    /// If so, it sets the corresponding values.
    /// Also, if WindowContent does not have a RegionManager attached, it creates a new scoped RegionManager for it.
    /// </summary>
    /// <param name="notification">The notification to be set as a DataContext in the HostWindow.</param>
    /// <param name="wrapperWindow">The HostWindow</param>
    protected void PrepareContentForWindow(Notification notification, Window wrapperWindow)
    {
        if (this.WindowContent == null)
        {
            return;
        }

        // We set the WindowContent as the content of the window. 
        wrapperWindow.Content = this.WindowContent;

        /* Code removed for brevity */

        // If the WindowContent implements IPopupWindowActionAware, we set the corresponding values.
        IPopupWindowActionAware popupAwareContent = this.WindowContent as IPopupWindowActionAware;
        if (popupAwareContent != null)
        {
            popupAwareContent.HostWindow = wrapperWindow;
            popupAwareContent.HostNotification = notification;
        }

        // If the WindowContent's DataContext implements IPopupWindowActionAware, we set the corresponding values.
        IPopupWindowActionAware popupAwareDataContext = this.WindowContent.DataContext as IPopupWindowActionAware;
        if (popupAwareDataContext != null)
        {
            popupAwareDataContext.HostWindow = wrapperWindow;
            popupAwareDataContext.HostNotification = notification;
        }
    }

    #endregion

    #region Window creation methods

    /// <summary>
    /// Returns the window to display as part of the trigger action.
    /// </summary>
    /// <param name="notification">The notification to be set as a DataContext in the window.</param>
    /// <returns></returns>
    protected Window GetWindow(Notification notification)
    {
        Window wrapperWindow;

        if (this.WindowContent != null)
        {
            wrapperWindow = new Window();
            wrapperWindow.WindowStyle = this.WindowStyle;
            // If the WindowContent does not have its own DataContext, it will inherit this one.
            wrapperWindow.DataContext = notification;
            wrapperWindow.Title = notification.Title ?? string.Empty;               

            this.PrepareContentForWindow(notification, wrapperWindow);
        }
        else
        {
            wrapperWindow = this.CreateDefaultWindow(notification);
            wrapperWindow.DataContext = notification;
        }

        return wrapperWindow;
    }

    private Window CreateDefaultWindow(Notification notification)
    {
        return new DefaultNotificationWindow 
        { 
            NotificationTemplate = this.ContentTemplate, 
            MessageBoxImage = GetImageFromNotification(notification as ZBaseNotification) 
        };
    }        

    #endregion
}

最佳答案

这里的根本问题是启动异步操作的代码和显示窗口的代码只是不合作。基于IPopupWindowActionAware 的设计恕我直言不太好;在常见情况下插入属性值是可以的,但在这里它开始显示其局限性。

让我们首先考虑一个适用于当前代码的本地化解决方案:

public Window HostWindow { /* call OnPropertyChanged! */ }

public void CompleteAction()
{
    if (this.HostWindow != null)
    {
        this.HostWindow.Close();
    }
    else
    {
        this.PropertyChanged += (o, e) => {
            if (e.PropertyName == "HostWindow" && this.HostWindow != null)
            {
                var hostWindow = this.HostWindow; // prevent closure-related bugs

                // kill it whenever it appears in the future
                hostWindow.Loaded += (o, e) => { hostWindow.Close(); };

                // kill it right now as well if it's been shown already
                // (we cannot assume anything)
                if (hostWindow.IsLoaded)
                {
                    hostWindow.Close();
                }
            }
        };
    }
}

这不是很优雅,但它完成了工作:如果在窗口已知之前调用 CompleteAction,那么当窗口已知时,我们附加一个处理程序,在它显示时立即关闭它.双深度事件处理程序分配是必要的,因为窗口在我们知道时可能不会显示。

关于c# - 使用 InteractionRequests 设计一个 "busy"对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876815/

相关文章:

c# - 在 MVC Controller 中加载 XML

c# - ASP.NET:ModalPopupExtender 阻止触发按钮单击事件

c# - 添加项目时,Observablecollection 不更新列表

.net - MVVM 中的事件而不是命令?

c# - 如何对在 MVVM 中调用异步方法的 DelegateCommand 进行单元测试

c# - 为什么不处理/关闭 SqlConnection?

c# - 接口(interface)的扩展方法是否被视为比不太具体的方法优先级低?

c# - Silverlight DataGrid 列验证

android - Xamarin.Forms MasterDetail 页面 NavBar 自定义

Prism:在一个区域中堆叠控件?