【问题标题】:How can I implement MVVM in Silverlight with Navigation service?如何使用导航服务在 Silverlight 中实现 MVVM?
【发布时间】:2012-05-30 16:00:59
【问题描述】:

我即将开始我的第一个 Silverlight 项目(Silverlight 4.0),并花了一些时间研究最佳方法等。我将使用 MVVM 并且最近几天一直在研究导航。

首先,我注意到很多 MVVM 示例没有将 MainPage 实现为视图/视图模型。 MainPage 包含导航框架和 Uri 映射,然后导航到遵循视图/视图模型的页面。使用 MVVM 和导航服务时,主页未实现为视图/视图模型是否标准?例如,Silverlight 4 培训工具包包含事件管理器示例,而主页背后有很多代码,即处理导航事件,如 Navigated 和 NavigatedFailed。但所有其他页面都是视图/视图模型。

其次,通过导航服务,更改导航的逻辑现在由视图完成,而不是由视图模型控制(这与 MVVM 背后的一些想法背道而驰)。网络上的一些方法使用从 ViewModel 到 View 的消息传递,或者将 Navigation 服务传递给 ViewModel 并在那里控制导航。这两种方法中的任何一种都比另一种更好吗?

理想情况下,我想找到一个示例,其中主页遵循 View/ViewModel 并且 ViewModel 控制导航并且 Views 没有后面的代码。我要求太多了吗??!

仅供参考,我没有使用 PRISM 或 MVVM Light。

干杯

【问题讨论】:

    标签: silverlight


    【解决方案1】:

    在我的项目中,我们在 MainPage 中创建了一个容器,每个视图都加载在那里。 这样我们就不需要在代码隐藏中放置任何代码。 当主页面在 App 上作为 RootVisual 启动时,MainPage 接收作为 DataContext 的类,我们在其中创建了一个 shell。容器从此类接收 DP,我们使用 shell 中的事件来加载视图。

    这是容器的代码:

    <ContentControl Name="region1ContentControl" Content="{Binding Path=MainContent}" Style="{StaticResource ContentControlStyle}" Grid.Row="1" Margin="0,30" />
    

    MainContent 属性:

    public static readonly DependencyProperty MainContentProperty =
            DependencyProperty.Register("MainContent", typeof(System.Windows.Controls.Control),
            typeof(MainPagePresenter), null);
        public System.Windows.Controls.Control MainContent
        {
            get { return (System.Windows.Controls.Control)GetValue(MainContentProperty); }
            set { SetValue(MainContentProperty, value); }
        }
    

    加载视图的shell +

    var presenter = (Bxf.IPresenter)Bxf.Shell.Instance;
    
            presenter.OnShowView += (view, region) =>
            {
                if (region.Equals("MainContent", StringComparison.InvariantCultureIgnoreCase))
                    MainContent = view.ViewInstance;
                else if (region.Equals("DetailContent", StringComparison.InvariantCultureIgnoreCase))
                    DetailContent = view.ViewInstance;
                else
                    throw new ArgumentException(string.Format(AppStrings.InvalidRegionName, region));
            };
    

    主页代码隐藏:

        public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }
    

    你看到了吗? 注意:我也没有使用 Prism 和 MVVM 灯。

    【讨论】:

    • 您好,Vinicius,感谢您的回复。我有点困惑 - 你的 MainPage 有相应的 ViewModel 吗?我也不知道如何控制导航。如果用户在浏览器中单击前进/后退,ViewModel 中是否会执行任何操作?
    • 我们的导航每次受限于一个视图。加载一个视图后,另一个视图将关闭。我们的 MainPage 有一个对应的 ViewModel(我们在其中创建了一个 shell),它作为 MainPage 的 DataContext 传递。在那里你可以做任何你想做的事情。
    猜你喜欢
    • 2011-05-02
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    相关资源
    最近更新 更多