MVVM关闭文件的方式有可能取消出来

And*_*ers 5 c# wpf mvvm avalondock caliburn.micro

我正在使用Avalondock 2.x作为我的一个开源项目,如果你关闭它时文档很脏,你应该可以取消关闭.

我正在使用Caliburn Micro和Coroutine,只有我能够解决它的方法是使用CM附加到事件

<i:EventTrigger EventName="DocumentClosing">
    <cal:ActionMessage MethodName="DocumentClosing">
        <cal:Parameter Value="$documentcontext" />
        <cal:Parameter Value="$eventArgs" />
    </cal:ActionMessage>
</i:EventTrigger>
Run Code Online (Sandbox Code Playgroud)

事件arg有取消属性.这个approuch的问题是它不是很MVVM友好,我已经创建了一个小帮手方法来Coroutinify这个像

public IEnumerable<IResult> Coroutinify(IEnumerable<IResult> results, System.Action cancelCallback)
{
    return results.Select(r =>
        {
            if (r is CancelResult)
                cancelCallback();

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

用过像

public IEnumerable<IResult> DocumentClosing(ScriptEditorViewModel document, DocumentClosingEventArgs e)
{
    return Result.Coroutinify(HandleScriptClosing(document), () => e.Cancel = true);
}
Run Code Online (Sandbox Code Playgroud)

这有效,但它有点笨拙等,是否有更多MVVM方式关闭Avalondock文件取消能力?

编辑:源代码

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.GUI/Shells/MainShellView.xaml#L29

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.GUI/Shells/MainShellViewModel.cs#L110

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.GUI/Result/ResultFactory.cs#L49

sfm*_*sfm 4

我实现此目的的方法是绑定到AvalonDock LayoutItem 的CloseCommand属性。当关联此绑定时,它会覆盖关闭文档的默认行为(“X”按钮,右键单击关闭/全部关闭)。如果需要,您将完全负责删除(关闭)该文档。

我设置它的方法是拥有一个包含 DocumentVM 的 ObservableCollection 的 DocumentManagerVM。每个 DocumentVM 都有一个名为 RequestCloseCommand 的 ICommand,它可以通过从其拥有的 DocumentManagerVM 的 DocumentVM 集合中删除自身来关闭文档。

具体来说,在我的 DocumentVM 视图模型中,有一个 ICommand(我使用 mvvmLight RelayCommand)来执行关闭逻辑:

public RelayCommand RequestCloseCommand { get; private set; }
void RequestClose()
{
    // if you want to prevent the document closing, just return from this function
    // otherwise, close it by removing it from the collection of DocumentVMs
    this.DocumentManagerVM.DocumentVMs.Remove(this);
}
Run Code Online (Sandbox Code Playgroud)

在您的视图中,在 LayoutItemContainerStyle 或 LayoutItemContainerStyleSelector 中设置绑定。

<ad:DockingManager
    DataContext="{Binding DocumentManagerVM}"
    DocumentsSource="{Binding DocumentVMs}">

    <ad:DockingManager.LayoutItemContainerStyle>
        <Style TargetType="{x:Type ad:LayoutItem}">
            <Setter Property="Title" Value="{Binding Model.Header}"/>
            <Setter Property="CloseCommand" Value="{Binding Model.RequestCloseCommand}"/>
        </Style>
    </ad:DockingManager.LayoutItemContainerStyle>

</ad:DockingManager>
Run Code Online (Sandbox Code Playgroud)