将ViewModel上的方法附加到WPF中的事件

时间:2009-09-01 11:11:07

标签: wpf events mvvm

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

我有一个ViewModel:

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

在DataTemplate中我得到了:

<TextBlock Text="{Binding Text}">

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

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

如果不在代码隐藏中创建回调,我无法弄清楚如何做到这一点。

2 个答案:

答案 0 :(得分:3)

使用来自here的AttachedCommandBehavior进行研究。它允许您完全在XMAL中将命令绑定到事件。不完全是你想要的,但它会给你相同的结果。

答案 1 :(得分:1)

我有一个适用于.NET 4.5+的新解决方案,在事件中使用自定义标记扩展。它可以与多个参数,绑定和其他扩展一起使用以提供参数值等。我在这里详细解释它:

http://www.singulink.com/CodeIndex/post/building-the-ultimate-wpf-event-method-binding-extension

用法:

tableViewController

查看模型方法签名:

<!--  Basic usage  -->
<Button Click="{data:MethodBinding OpenFromFile}" Content="Open" />

<!--  Pass in a binding as a method argument  -->
<Button Click="{data:MethodBinding Save, {Binding CurrentItem}}" Content="Save" />

<!--  Another example of a binding, but this time to a property on another element  -->
<ComboBox x:Name="ExistingItems" ItemsSource="{Binding ExistingItems}" />
<Button Click="{data:MethodBinding Edit, {Binding SelectedItem, ElementName=ExistingItems}}" />

<!--  Pass in a hard-coded method argument, XAML string automatically converted to the proper type  -->
<ToggleButton Checked="{data:MethodBinding SetWebServiceState, True}"
                Content="Web Service"
                Unchecked="{data:MethodBinding SetWebServiceState, False}" />

<!--  Pass in sender, and match method signature automatically -->
<Canvas PreviewMouseDown="{data:MethodBinding SetCurrentElement, {data:EventSender}, ThrowOnMethodMissing=False}">
    <controls:DesignerElementTypeA />
    <controls:DesignerElementTypeB />
    <controls:DesignerElementTypeC />
</Canvas>

    <!--  Pass in EventArgs  -->
<Canvas MouseDown="{data:MethodBinding StartDrawing, {data:EventArgs}}"
        MouseMove="{data:MethodBinding AddDrawingPoint, {data:EventArgs}}"
        MouseUp="{data:MethodBinding EndDrawing, {data:EventArgs}}" />

<!-- Support binding to methods further in a property path -->
<Button Content="SaveDocument" Click="{data:MethodBinding CurrentDocument.DocumentService.Save, {Binding CurrentDocument}}" />