繁体   English   中英

如何在WPF MVVM中将View变量绑定到ViewModel?

[英]How to bind Variables of View to ViewModel in WPF MVVM?

我创建了一个窗口(WPF和MVVM)-说PrintWidow(所以我有PrintWindow.xaml,PrintWindow.xaml.cs,PrintWindowViewModel.cs- viewmodel)

现在,我将在单击按钮或通过某些命令触发器使用其他类中的(调用)此PrintWindow obj时,我想为此PrintWindow设置Document Source(在MVVM之后)。

我该怎么做? 我在PrintWindow.xaml.cs中创建了一个PrintDocument对象,并尝试按以下方式绑定它:(显然只是一个空的尝试-因为我不能在XAML中进行此声明)

private PrintDocument printDocuementView;

public PrintDocument PrintDocuement
{
    get { return printDocuementView; }
    set { printDocuementView = value; }
}

//constructor
public PrintWindow()
{
    InitializeComponent();
    this.DataContext = new PrintViewModel();

    Binding b = new Binding();
    b.Source = printDocuementView;
    b.Path = new PropertyPath("PrintDocumentCommand"); // "PrintDocumentCommand" is defined in View Model class and is responsible to set the `PrintDocument` object there.

}

该代码(显然)不起作用。 我应该怎么做。 简介:我想从另一个窗口打开PrintWindow ,并最终从``其他寡妇''对象后面的代码中设置PrintWindow某些属性。查询是-该属性应该放在哪里? 查看? ViewModel? ?? 令人费解

我已经用Google搜索了答案-但无法与我的问题有关。

我是WPF的新生,也是MVVM的新秀。

由于您的PrintDocumentCommand是在你的PrintViewModel但你设定的这种结合的实例源PrintDocument级轿车,它不能被发现,因为绑定正在寻找PrintDocumentCommandPrintDocument -Class。

如果要从另一个窗口打开PrintWindow,请将PrintDocument -Property和PrintDocumentCommand放在另一个窗口的ViewModel中。 现在,通过PrintDocumentCommand执行的函数可能类似于:

private void Print()
{
    PrintWindow pw = new PrintWindow(PrintDocument);
    pw.ShowDialog();
}

您的PrintView的构造函数可能类似于:

public PrintWindow(PrintDocument pd)
{
    InitializeComponents();
    this.DataContext = new PrintViewModel(pd);
}

现在您可以在PrintViewModel中访问PrintDocument。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM