使用InteractionRequests设计“忙”对话框

时间:2013-02-14 14:16:29

标签: c# mvvm prism prism-4 interaction

我目前正在使用Prism的InteractionRequest来显示新窗口。我使用它们进行简单的确认,并在sample here之后显示带有自定义视图/视图模型的窗口窗口。无论如何,在所有这些情况下,我显示窗口,窗口上的一些按钮负责关闭它。我想显示一个窗口,并让调用它的对象负责关闭它。

这是我的实施:

ActionNotification

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之前完成“工作”时我会很糟糕。任何人都可以向保证提供一些建议,要么在提出请求之前工作尚未完成,否则不要突袭请求?

编辑:我应该补充一点,窗口显示为模态,因此在引发请求后不会执行任何代码,这就是我将工作推送到单独任务的原因

EDIT2:以下是视图与请求的互动方式:

<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
}

1 个答案:

答案 0 :(得分:1)

这里的根本问题是启动异步操作的代码和显示窗口的代码只是不合作。基于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,那么当窗口变为已知时,我们会附加一个处理程序,只要它显示就会立即关闭它。双深度事件处理程序分配是必要的,因为窗口可能在我们不知道时显示。