WPF,MVVM:创建新视图并将参数传递给其ViewModel

时间:2018-05-09 11:15:23

标签: c# wpf mvvm

我在任何地方都找不到这个。目前我正在制作一个WPF应用程序,但我遇到了一个问题。我需要一个页面,但数据应该是不同的,这取决于召唤页面的按钮。如果不想坚持使用MVVM,那将会很容易。我已经有一个按钮将所需的数据传递给页面cs文件,但我不知道如何将该数据传递给ViewModel。

DetailedViewPage.xaml.cs:

namespace unnamed
{
    public partial class DetailedViewPage : BasePage<DetailedViewViewModel>
    {    
        public DetailedViewPage(string position)
        {    
            InitializeComponent();
        }
    }


    //I'm using similar method to create new View
    private void CreateNewWindow()
    {
        var MainWindow = (MainWindow) Application.Current.MainWindow;
        var MWViewModel = (WindowViewModel) MainWindow.DataContext;
        MWViewModel.CurrentPage = new DetailedViewPage("top");
    }

}

BasePage.cs:

public class BasePage<VM> : Page
        where VM : BaseViewModel, new()
    {

        private VM mViewModel;

        public VM ViewModel
        {
            get { return ViewModel; }
            set
            {
                if (mViewModel == value)
                    return;
                mViewModel = value;
                this.DataContext = mViewModel;
            }
        }

        public BasePage()
        {
            this.Resources = ((MainWindow)Application.Current.MainWindow).Resources;
            this.ViewModel = new VM();
        }
    }

DetailedViewViewModel.cs:

namespace unnamed
{
    public class DetailedViewViewModel : BaseViewModel
    {    
        public string PossitionShown { get; set; }

        public DetailedViewViewModel()
        {                
        }    
    }
}

所以我的目标是从页面cs文件到ViewModel获取该位置变量并分配给PossitionShown

1 个答案:

答案 0 :(得分:0)

您的观点(DetailedViewPage)有一个DataContext,即DetailedViewViewModel

DataContext可以通过默认构造函数自动创建(在XAML中输入时),也可以在构造函数中创建。基本上,在创建视图之后,我们只需将值设置为它即可。

public DetailedViewPage(string position)
{
    InitializeComponent();

    //optional line, if not set in XAML
    this.DataContext = new DetailedViewViewModel();

    var VM = (this.DataContext as DetailedViewModel);
    VM.PossitionShown = position;
}

修改 添加代码以在ViewModel构造中传递变量。

public DetailedViewPage(string position)
{
    InitializeComponent();
    //Note this line is not "optional" anymore, You must pass the value as a variable.
    this.DataContext = new DetailedViewViewModel(position);
}

public class DetailedViewViewModel : BaseViewModel
{
    public string PossitionShown { get; set; }
    public DetailedViewViewModel(string position)
    {
        PossitionShown = position;
    }
}

作为旁注,这不是完全MVVM approach,因为您已经通过View传递了一些参数,View正在考虑存在某种类型的{{1} }}

关于这个主题,我建议通过: