Caliburn Micro自我替换View / ViewModel

时间:2014-12-11 21:21:43

标签: wpf caliburn.micro

我有一个列表框来选择要编辑的项目。我也有一个编辑按钮。将其称为MainView [Model]。

如果按下编辑按钮,MainView [Model]将被EditView [Model]替换。 EditView不会显示在MainView下方或旁边的区域中。它应该被完全替换或至少完全隐藏MainView。

如果编辑完成(OK,取消),MainView将再次显示。

我试图覆盖ContentControl但没有成功。 现在,我正在考虑一种NavigatorViewModel,它有一个属性公开的多个ViewModel。但我不确定这是否是正确的方向。

有人可以帮忙吗?

THX。

1 个答案:

答案 0 :(得分:0)

您最好使用Caliburn.Micro提供的导体图案。导体管理一个或多个屏幕并控制它们的寿命。有关详细信息,请参阅Screens, Conductors and Composition

  1. 首先,我们需要一个shell。这是你的&#34; NavigatorViewModel&#34;。它源自Conductor<Screen>.Collection.OneActive,这意味着它包含一个屏幕列表,其中一个屏幕可以一次处于活动状态:

    public interface IShell
    {
        void ActivateItem(Screen screen);
    }
    
    public class ShellViewModel : Conductor<Screen>.Collection.OneActive, IShell
    {
        public ShellViewModel()
        {
            this.ActivateItem(new MainViewModel());
        }
    }
    
  2. 指挥有一个ActiveItem属性,我们想要ContentControl绑定它,所以我们看到相应的视图:

    <!-- ShellView.xaml -->
    <Window x:Class="WpfApplication1.ShellView"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
        <ContentControl Name="ActiveItem" />
    
    </Window>
    
  3. 我们的MainViewModel可以使用其父级shell导航到EditViewModel

    public class MainViewModel : Screen
    {
        public void Edit()
        {
            ((IShell)this.Parent).ActivateItem(new EditViewModel());
        }
    }
    
  4. 我们将按钮绑定到Edit方法:

    <!-- MainView.xaml -->
    <UserControl x:Class="WpfApplication1.MainView"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
        <Button Name="Edit" Content="Edit" />
    
    </UserControl> 
    
  5. EditViewModel也派生自Screen,只包含您的编辑逻辑:

    public class EditViewModel : Screen
    {
    }
    
  6. 最后,我们将一个按钮绑定到TryClose方法,因此视图模型会自行关闭并从shell的项目中删除。最后激活的项目(MainViewModel)将被重新激活:

    <!-- EditView.xaml -->
    <UserControl x:Class="WpfApplication1.EditView"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
        <Button Name="TryClose" Content="Back" />
    
    </UserControl>
    
  7. 关于它。

相关问题