在MVC中连接事件处理程序的MVVM方式 [英] MVVM way to wire up event handlers in Silverlight

查看:113
本文介绍了在MVC中连接事件处理程序的MVVM方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Silverlight / WPF中使用MVVM模式,如何连线事件处理程序?我试图将XAML 单击属性绑定到视图模型中的代理,但无法使其正常工作。



换句话说,我想替换:

  ; Button Content =Test ClickClick =Button_Click/> 

其中Button_Click是:

  private void Button_Click(object sender,RoutedEventArgs e)
{
// ...
}

与此:

 < Button Content =测试点击click ={Binding ViewModel.HandleClick}/> 

其中HandleClick是处理程序。尝试这会抛出一个运行时异常:


类型System.Windows.Data.Binding的对象不能转换为类型'System.Windows .RoutedEventHandler'。



解决方案

MVVM的方法是使用命令和< a href =http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx =nofollow> ICommand 接口。
按钮控件有一个名为的属性命令,它接收一个类型为的对象ICommand



常用的 ICommand 的实现是 Prism's DelegateCommand 。要使用它,您可以在视图模型中执行此操作:

  public class ViewModel 
{
public ICommand DoSomethingCommand {get;私人集合}

public ViewModel()
{
DoSomethingCommand = new DelegateCommand(HandleDoSomethingCommand);
}

private void HandleDoSomethingCommand()
{
//做东西
}
}

然后在XAML中:

  Button Content =Test ClickCommand = {Binding DoSomethingCommand} /> 

另外,请确保将viewmodel设置为视图的DataContext。一种方法是在您的视图的代码隐藏中:

  this.DataContext = new ViewModel(); 

如果您想了解有关MVVM的更多信息,这篇文章是一个很好的起点。


Using an MVVM pattern in Silverlight/WPF, how do you wire up event handers? I'm trying to bind the XAML Click property to a delegate in the view model, but can't get it to work.

In other words, I want to replace this:

<Button Content="Test Click" Click="Button_Click" />

where Button_Click is:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    // ...
}

with this:

<Button Content="Test Click" Click="{Binding ViewModel.HandleClick}" />

where HandleClick is the handler. Attempting this throws a runtime exception:

Object of type 'System.Windows.Data.Binding' cannot be converted to type 'System.Windows.RoutedEventHandler'.

解决方案

The MVVM way to do so is by using commands and the ICommand interface. The Button control has a property named Command which receives an object of type ICommand

A commonly used implementation of ICommand is Prism's DelegateCommand. To use it, you can do this in your view model:

public class ViewModel
{
    public ICommand DoSomethingCommand { get; private set; }

    public ViewModel()
    {
        DoSomethingCommand = new DelegateCommand(HandleDoSomethingCommand);
    }

    private void HandleDoSomethingCommand()
    {
        // Do stuff
    }
}

Then in XAML:

<Button Content="Test Click" Command={Binding DoSomethingCommand} />

Also, make sure that the viewmodel is set as your view's DataContext. One way to do so is in your view's code-behind:

this.DataContext = new ViewModel();

This article is a good place to start if you want to know more about MVVM.

这篇关于在MVC中连接事件处理程序的MVVM方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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