简体   繁体   中英

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

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM