wpf mvvm .. 访问视图模型中的视图元素

问题描述:

我正处于学习 wpf/mvvm 的阶段,因为我在 vm 中了解到我们声明命令并将它们绑定到查看元素的事件而不是在代码隐藏文件中执行此操作...我没有得到的是,我们将如何访问查看元素和事件参数.

I am in phase of learning wpf/mvvm as per i get to know in vm we declare commands and bind them to view element's event rather doing this in codebehind file... what i am not getting is, how would we access view elements and eventarguments.

您的 ViewModel 不会直接访问 View 中的元素.这个概念是 View 将绑定到 ViewModel,而不是相反.所以;您的 ViewModel 将通过属性中设置的值告诉 View 要显示什么.如果您的 View 需要显示某些内容,它将对提供此内容的属性进行数据绑定.

Your ViewModels won't access the elements in the View directly. The concept is that the View will bind to the ViewModel, and not the other way around. So; your ViewModel will tell the View what to display through values set in properties. If your View needs to display something it will have a databinding to the property giving this.

命令将由 ViewModel 保存,您也可以直接绑定它们.如果您需要命令来更新视图的值,这可以通过保存从命令到必要的 ViewModel 的引用来完成.(持有命令的 ViewModel 可以例如在创建时将自身注入命令).然后命令可以告诉 ViewModel 更新一些东西,这将通过数据绑定反映在 View 中.

The commands will be held by a ViewModel, and you can bind them too directly. If you need the command to update values for the View this can be done by holding a reference from the command to the necessary ViewModel. (The ViewModel holding the Command can e.g. inject itself to the command on creation). Then the command can tell the ViewModel to update something, and this will be reflected in the View through data bindings.

有关 MVVM 模式的一般介绍,您可以查看几天前提出的这个问题:为 WPF 学习 MVVM.

For general introduction to the MVVM pattern you can check out this question which was asked a few days ago: Learning MVVM for WPF.