【问题标题】:Caliburn Micro self-replacing View/ViewModelCaliburn Micro 自替换 View/ViewModel
【发布时间】:2014-12-11 21:21:42
【问题描述】:

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

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

如果编辑完成(确定,取消)主视图将再次显示。

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

有人可以帮忙吗?

谢谢。

【问题讨论】:

  • 这只是一个视图切换的例子。它可以是完全不同的视图/视图模型配对。您只需要简单地找出一种方法来传递要编辑的项目的索引或 id。

标签: wpf caliburn.micro


【解决方案1】:

您最好使用 Caliburn.Micro 提供的导体模式。指挥员管理一个或多个屏幕并控制它们的寿命。请参阅Screens, Conductors and Composition 了解更多信息。

  1. 首先,我们需要一个外壳。这是您的“NavigatorViewModel”。它源自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 方法,因此视图模型会自行关闭并从外壳的项目中移除。最后激活的项目 (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>
    

就是这样。

【讨论】:

  • 太棒了!非常感谢!
猜你喜欢
  • 2019-01-01
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
  • 2013-12-30
  • 2013-06-26
  • 1970-01-01
  • 2020-10-24
  • 2015-12-06
相关资源
最近更新 更多