ViewModel如何在WPF/MVVM中的视图中请求更新? [英] How can the ViewModel request an update in the View in WPF/MVVM?

查看:98
本文介绍了ViewModel如何在WPF/MVVM中的视图中请求更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在View的控件上有一个依赖项属性,该属性绑定到ViewModel上的一个字段.当用户单击菜单项时,我希望控件更新该属性的值,以便ViewModel可以将其保存在XML文件中.请问ViewModel请求View更新该属性的正确机制是什么?


将代码从下面的注释中移出

I have a dependency property on a control in my View that is bound to a field on my ViewModel. When the user clicks a menu item I want the control to update the value of that property so the ViewModel can save it in an XML file. What is the correct mechanism to have the ViewModel request that the View update that property?


move the code from comment below

The XAML:
	
   "open bracket" controls:MyControl 
   MyProperty="{Binding MyProperty, Mode=TwoWay}" "close bracket"
			
   MyControl class:
	
   public static readonly DependencyProperty MyPropertyProperty =
      DependencyProperty.Register("MyProperty",
                  typeof(byte[]),
                  typeof(MyControl),
                  new PropertyMetadata(null)
                  );
				  
   ViewModel property:
	byte [] MyProperty {get;set;}
			

// Code on ViewModel that is run when the MenuItem is clicked:
	
   public void MyMenuItemFunction()
   {
      // Get the up-to-date value of MyProperty from MyControl here
   }

推荐答案

您应该使用命令绑定. ViewModel将公开ICommand属性.您将从ICommand派生一个将处理Execute的类.当从ViewModel实例化命令对象时,您可以将所需的其他任何内容传递到其中.

然后,菜单命令可以通过其Command属性使用绑定.然后在按下时将调用您的Execute方法.
You should use command binding. The ViewModel would expose an ICommand property. You would derive a class from ICommand that will handle the Execute. When you instantiate the command object from your ViewModel, you can pass anything else you need into there.

The menu command can then use binding via its Command property. That will then call your Execute method when pressed.


这篇关于ViewModel如何在WPF/MVVM中的视图中请求更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆