How to add event handler in MVVM in Windows Phone 8?

1.1k Views Asked by At

All

I have a issue. Now I'm using MVVM framework to develop Windows Phone 8 app. I just want to when I press the button, then begin to record something, when release the button, stop recording, I used InvokeCommandAction to bind the command in ViewModel, this is the code as follow

Xaml:

<Button x:Name="BtnRecord" Height="50" Width="180" Background="#D43637" Content="Record" Margin="20,0,0,0" Style="{StaticResource BasicButtonStyle}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding StartRecordCommand}"/>
         </i:EventTrigger>
        <i:EventTrigger EventName="MouseLeftButtonUp">
            <i:InvokeCommandAction Command="{Binding EndRecordCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

ModelView:

public ICommand StartRecordCommand
{
    get
    {
        return new DelegateCommand(StartRecord);
    }
}

public ICommand EndRecordCommand
{
    get
    {
        return new DelegateCommand(EndRecord);
    }
}

private void StartRecord(object parameter){}

private void EndRecord(object parameter){}

When I debug the app, I found it didn't fire the neither the MouseLeftButtonDown nor MouseLeftButtonUp events, so I register the two event handler as follow:

BtnRecord.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(Button_MouseLeftButtonDown), true);
BtnRecord.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), true);

private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}
private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
}

OK, keep on going, but the next problem is coming, it didn't fire the ICommand in ViewModel, it called the Button_MouseLeftButtonDown, oh, god, I crazy

Anyone know how to call the ICommand in ViewModel? Or another way to implement it?

2

There are 2 best solutions below

0
On BEST ANSWER

You can use ICommand.Execute. So, your handler should be

private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    StartRecordCommand.Execute(null);
}
0
On

Try binding the IsPressed property of the Button with a TwoWay binding to a bool property called IsRecording in your ViewModel and start/stop your recording logic from inside the setter based on the new bool value (true would mean start). Let me know if it works.