【问题标题】:How to bind Variables of View to ViewModel in WPF MVVM?如何在 WPF MVVM 中将 View 的变量绑定到 ViewModel?
【发布时间】:2013-09-06 06:52:40
【问题描述】:

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

现在我要使用(调用)这个PrintWindow obj 来自其他类的按钮单击或某个命令触发器,我想为此 PrintWindow 设置文档源(跟随 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 的一些属性。查询是-这个属性应该去哪里?看法 ?视图模型? ?? 困惑

我已经用谷歌搜索了答案 - 但无法与我的问题联系起来。

我是WPF 的新生和MVVM 的新秀。

【问题讨论】:

  • 你想达到什么目的?您想从另一个窗口打开 PrintWindow 吗?还是要在 PrintWindow 中添加一个按钮来激活某些功能?
  • 看看这个MVVM Tutorial
  • @bitestar:我想从另一个窗口打开打印窗口。并最终从后面的代码或“其他寡妇”中设置源文档。

标签: c# .net wpf xaml mvvm


【解决方案1】:

由于您的PrintDocumentCommand 在您的PrintViewModel 中,但是您将此绑定的源设置为PrintDocument-Class 的实例,因此无法找到它,因为绑定正在寻找@ 987654324@ 在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。

【讨论】:

  • 我不明白 - 如果我删除 b.source,我会将我的 PrintDocumentCommand 绑定到什么。其余的我已经在做。
  • 我想我误解了你想要做什么,看看我的编辑;)
  • 谢谢,为我工作(尽管对我的项目进行了很少的改动)-但是 Workd。 :)
猜你喜欢
  • 1970-01-01
  • 2011-11-07
  • 2011-02-08
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多