CallMethodAction绑定到Button失败

时间:2017-07-25 10:51:29

标签: c# wpf mvvm

没有错误。我正在努力学习MVVM。设置很简单。单击按钮时没有输出。 Xaml应该没问题,因为我通过将行为拖动到按钮来生成Blend中的交互部分。注意:我打算使用方法,但不使用命令,因为命令仅包含点击,但不包括例如DoubleClick。

<Window
x:Class="MVVM_1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:local="clr-namespace:MVVM_1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d"
 >
<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
<Grid>
    <Button  x:Name="button"
        Width="75"
        Margin="198,168,0,0"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Content="TestMethod">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseLeftButtonDown" SourceName="button">
                <ei:CallMethodAction MethodName="MethodTesting" 
                                     TargetObject="{Binding}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>
</Grid>

using System.Windows;

namespace MVVM_1
{
public class ViewModel 
    {

    public static void MethodTesting()
        {
            MessageBox.Show("Success!");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使用命令将控件绑定到click事件。

MVVM - Commands, RelayCommands and EventToCommand

而不是:

public static void MethodTesting()  
{
    MessageBox.Show("Success!");
}

使用this example

public ICommand ButtonClickCommand 
{
    get { return new DelegateCommand<object>(FuncToCall, FuncToEvaluate);}
}

private void FuncToCall(object context)
{
    //this is called when the button is clicked
    MessageBox.Show("Success!");
}

private bool FuncToEvaluate(object context)
{
    //this is called to evaluate whether FuncToCall can be called
    //for example you can return true or false based on some validation logic
    return true;
}

此下还有How do you create an OnClick command in WPF MVVM with a programmatically created button? - is another great example