防止文档关闭在DockingManager



下面是一个示例,它使用扩展WPF工具包中的DockingManager(又名AvalonDock)。

视图模型:

public class Person
{
    public string Name { get; set; }
    public bool CanClose { get; set; }
}

视图:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:xcad="http://schemas.xceed.com/wpf/xaml/avalondock"
        xmlns:local="clr-namespace:WpfApplication2">
    <Grid>
        <xcad:DockingManager DocumentsSource="{Binding}">
            <xcad:DockingManager.Resources>
                <DataTemplate DataType="{x:Type local:Person}">
                    <StackPanel>
                        <TextBlock Text="Here's person name:"/>
                        <TextBlock Text="{Binding Name}"/>
                    </StackPanel>
                </DataTemplate>
            </xcad:DockingManager.Resources>
            <xcad:DockingManager.DocumentHeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Content.Name}" />
                </DataTemplate>
            </xcad:DockingManager.DocumentHeaderTemplate>
            <xcad:LayoutRoot>
                <xcad:LayoutPanel Orientation="Horizontal">
                    <xcad:LayoutDocumentPane />
                </xcad:LayoutPanel>
            </xcad:LayoutRoot>
        </xcad:DockingManager>
    </Grid>
</Window>

后台代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new[]
        {
            new Person { Name = "John" },
            new Person { Name = "Mary", CanClose = true },
            new Person { Name = "Peter", CanClose = true },
            new Person { Name = "Sarah", CanClose = true },
        };
    }
}

我想防止文档通过我的视图模型中的CanClose属性关闭。我已经预料到,必须有一些样式的文档容器,所以,我将这样写:

<Setter Property="CanClose" Value="{Binding Content.CanClose}"/>

,一切都会正常工作。但是看起来在DockingManager中没有这样的风格。

我错过了什么吗?

当然,我可以编写一个附加的行为,它将侦听DockingManager.DocumentClosing事件并将其分派到任何视图模型,该模型将绑定到DockingManager。但在我看来,这是非常愚蠢的……

另一种方法是在视图中处理事件:
private void DockingManager_DocumentClosing(object sender, Xceed.Wpf.AvalonDock.DocumentClosingEventArgs e)
{
    e.Cancel = !((Person)e.Document.Content).CanClose;
}

但这绝对不是mvvm方式,我喜欢数据绑定。

如果你有一个ContentViewModel -你可以有一个ICommand Close {get;set;}属性,并将其绑定到LayoutItem的Close命令。

你可以在你的ContentViewModel上使用一个DelegateCommand来决定你是否可以关闭文档(设置e.Cancel = true应该会停止关闭命令)。

最新更新