MVVM - 打开第二视图Windows 8

时间:2013-04-02 14:22:00

标签: c# windows mvvm view viewmodel

编辑:示例应用 - > http://www10.zippyshare.com/v/29730402/file.html

我正在编写适用于Windows 8和Windows的应用程序Windows Phone。我正在使用便携式类库(请参阅此文章http://blog.tattoocoder.com/2013/01/portable-mvvm-light-move-your-view.html)。

我的问题是:如何通过使用MVVM模式单击按钮来打开第二个窗口?我不想在后面的代码中这样做。

我的Windows 8应用程序的datacontext在xaml中看起来像这样

DataContext="{Binding Main, Source={StaticResource Locator}}"

使用PCL的ViewModel(= ViewModel for W8& WP8)

xmlns:vm="using:Mvvm.PCL.ViewModel" 

我不知道如何将2个datacontext分配给我的MainPage.xaml,也不知道如何将我的MainPage.xaml分配给我的Windows 8应用程序的ViewModel。

我尝试过这样的事情:

Command="{Binding DisplayView}" CommandParameter="SecondView"

但程序使用ViewModel用于两个平台,我无法在那里为特定平台编写Windows分配。 (它应该看起来像这样Opening multiple views by clicking button using MVVM silverlight approach ...)

说清楚:

我有2个项目。 项目的两个MainWindows都引用“MainProject”的ViewModel。 如果我想点击MainWindow中的一个按钮,我想打开一个新视图,但我只能将ViewModel用于这两个项目,这意味着我无法在我的ViewModel中使用2个项目的任何视图“MainProject”。

编辑:我见过很多人都使用ContentControl。 (仍然无法正常工作。对于MVVM来说是新手。)

<ContentControl Grid.Row="2" Content="{Binding CurrentView}" IsTabStop="False" Margin="10" />
<Button Command="{Binding DisplayView}" CommandParameter="SecondView">

MainViewModel.cs(适用于两个平台)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Mvvm.PCL.Model;
#if NETFX_CORE 
    using Mvvm.Store.Views;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
#endif

namespace Mvvm.PCL.ViewModel
{

public class MainViewModel : ViewModelBase, INotifyPropertyChanged
{
    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>

    public MainViewModel()
    {
#if NETFX_CORE
        DisplayView = new RelayCommand<string>(DisplayViewCommandExecute);
#endif
        }

    #region Commands

    public RelayCommand<string> DisplayView { get; private set; }

    #endregion

#if NETFX_CORE

    #region CurrentView Property

    public const string CurrentViewPropertyName = "CurrentView";

    private Page _currentView;

    public Page CurrentView
    {
        get { return _currentView; }
        set
        {
            if (_currentView == value)
                return;

            _currentView = value;
            RaisePropertyChanged(CurrentViewPropertyName);
        }
    }

    private SecondView _secondview = new SecondView();
    public SecondView SecondView
    {
        get
        {
            return _secondview;
        }
    }

    #endregion

    private void DisplayViewCommandExecute(string viewName)
    {
        switch (viewName)
        {
            case "SecondView":
                CurrentView = _secondview;
                var frame = (Frame)Window.Current.Content;
                frame.Navigate(typeof(SecondView));
                break;
        }
    }
#endif
}
}

0 个答案:

没有答案