将ViewModel上的方法附加到WPF中的事件 [英] Attach method on ViewModel to events in WPF

查看:110
本文介绍了将ViewModel上的方法附加到WPF中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将WPF控件上的事件绑定到ViewModel上的方法?

How can bind an event on a WPF Control to a method on my ViewModel?

我有一个ViewModel:

I have a ViewModel:

class MyViewModel {
    public string MyText { get; set; }
    public void MyMouseHandleMethod(object sender, EventArgs e) { }
}

在DataTemplate中,我得到了:

In a DataTemplate I've got:

<TextBlock Text="{Binding Text}">

现在,我想将ViewModel上的方法附加到TextBlock上,例如:

Now I would like to attach a method on my ViewModel to the TextBlock, something like:

<TextBlock Text="{Binding MyText}" MouseUp="{Binding MyMouseHandleMethod}">

如果不在后台代码中创建回调,我无法弄清楚该怎么做.

I cannot figure out how to do this without creating a callback in the Code-behind.

推荐答案

Look into using AttachedCommandBehavior from here. It allows you to bind Commands to events entirely in XMAL. Not exactly what you want, but it will give you the same outcome.

这篇关于将ViewModel上的方法附加到WPF中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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