[英]How to add event handler in MVVM in Windows Phone 8?
所有
我有一个问题。 现在,我正在使用MVVM框架来开发Windows Phone 8应用程序。 我只是想当我按下按钮时,然后开始记录一些东西,当释放按钮时,停止记录,我使用了InvokeCommandAction来绑定ViewModel中的命令,这是下面的代码
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>
模型视图:
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){}
当我调试应用程序时,我发现它没有触发MouseLeftButtonDown和MouseLeftButtonUp事件,因此我按如下方式注册了两个事件处理程序:
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)
{
}
好的,继续前进,但是下一个问题来了,它没有触发ViewModel中的ICommand,它名为Button_MouseLeftButtonDown,哦,天哪,我疯了
有人知道如何在ViewModel中调用ICommand吗? 还是另一种实现方式?
您可以使用ICommand.Execute
。 所以,您的经理应该
private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
StartRecordCommand.Execute(null);
}
尝试将具有DoubleWay的Button的IsPressed属性绑定到ViewModel中名为IsRecording的bool属性,并基于新的bool值从设置器内部启动/停止记录逻辑(true表示开始)。 让我知道它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.