我创建了一个窗口( WPF 和 MVVM ) - 说 PrintWidow (所以我有 PrintWindow.xaml , PrintWindow.xaml.cs , PrintWindowViewModel.cs- viewmodel)
现在我要使用(调用)这个 PrintWindow
在按钮单击或某些命令触发器上来自其他类的 obj ,我想为此 PrintWindow 设置文档源(在 MVVM 之后)。
我该怎么做?我创建了一个 PrintDocument
PrintWindow.xaml.cs 中的对象并尝试按如下方式绑定(bind)它:(显然只是一个空白尝试 - 因为我无法在 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
的某些属性来自“其他寡妇”对象后面的代码。查询是 - 这个属性应该去哪里?看法 ? View 模型? ??百思不得其解我已经用谷歌搜索了答案 - 但无法与我的问题联系起来。
我是
WPF
的新生和 MVVM
的新秀.
最佳答案
由于您的PrintDocumentCommand
在您的 PrintViewModel
中但是您将此绑定(bind)的源设置为 PrintDocument
的实例-Class,找不到,因为Binding正在寻找PrintDocumentCommand
在 PrintDocument
-类(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。
关于c# - 如何在 WPF MVVM 中将 View 的变量绑定(bind)到 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651664/