c# - 如何在 WPF MVVM 中将 View 的变量绑定(bind)到 ViewModel?

标签 c# .net wpf xaml mvvm

我创建了一个窗口( 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正在寻找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。

关于c# - 如何在 WPF MVVM 中将 View 的变量绑定(bind)到 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651664/

相关文章:

c# - VS 2010、NUNit 和 "The breakpoint will not currently be hit. No symbols have been loaded for this document"

.net - 在WPF中创建吉他和弦编辑器(来自RichTextBox?)

c# - 如何使用反射将新项目添加到集合中

c# - 多少层太多了?

c# - 无法转换到 VisualState - "No applicable name scope"

c# - Xamarin.Forms - 使用枚举作为触发器

c# - 如何使用 RadioButton 使其他 RadioButton 可见?

c# - Lambda 表达式和 || Entity Framework 中的运算符

c# - ASP :gridview filter using listbox cannot make multiple selection

.net - System.Windows.Forms.Keys枚举中的 “OEM”键是什么?