简体   繁体   English

单击按钮时取消命令

[英]Cancel command on button click

I currently have a windows phone 8 application that has a user control that is bound to some view model. 我目前有一个Windows Phone 8应用程序,该应用程序具有绑定到某些视图模型的用户控件。 In the view model I a have a command property that binds to a button on the view. 在视图模型中,我具有一个命令属性,该属性绑定到视图上的按钮。

I want to popup a message box in the view that asks "Are you sure you want to do X?". 我想在视图中弹出一个消息框,询问“您确定要执行X吗?”。 If Yes it needs to fire the command that is bound to the button else it needs to not fire the command. 如果是,则需要触发绑定到该按钮的命令,否则无需触发该命令。

I obviously do not want to fire the MessageBox from the view model since this is view logic. 我显然不想从视图模型中触发MessageBox,因为这是视图逻辑。 So how do I show the MessageBox in the view and then not fire the command that it is bound to it. 因此,如何在视图中显示MessageBox,然后不触发与其绑定的命令。

Edit: Let me just make it clear. 编辑:让我澄清一下。 The command is in the viewmodel and bound in xaml. 该命令位于视图模型中,并以xaml绑定。 The MessageBox show is in the view code behind (in the buttons's click event). MessageBox显示在后面的视图代码中(在按钮的click事件中)。 I would like to keep it like this. 我想保持这样。 My question is just. 我的问题是。 How do I not fire the command once the botton is pressed and the MessageBox returns Cancel. 一旦按下botton并且MessageBox返回Cancel,如何不触发命令。

Ok so I have found a solution. 好的,所以我找到了解决方案。

I created a new UserControl: ConfirmationButton with a dependency ICommand property for if the confirmation passed. 我创建了一个新的UserControl:ConfirmationButton,它具有依赖项ICommand属性,用于确认是否通过。 In the control I manually fire the command if the MessagBox Returns Yes. 如果MessagBox返回“是”,则在控件中手动触发命令。 I then use this new UserControl where I need such functionality. 然后,在需要此类功能的地方使用新的UserControl。

You can do it on click event of the button. 您可以在按钮的单击事件上执行此操作。 you can popup the message box in click event handler. 您可以在单击事件处理程序中弹出消息框。 If user wants to cancel the operation than simply set the e.handle = true. 如果用户想取消操作,则只需设置e.handle = true。

If you don't want to use code-behind, you can create your own custom button where you can override OnClick() method of the button. 如果您不想使用后台代码,则可以创建自己的自定义按钮,在其中可以覆盖按钮的OnClick()方法。 In the method show the message box and if user wants to cancel the event, just don't call base.OnClick(); 在显示消息框的方法中,如果用户要取消事件,则不要调用base.OnClick();。

You can refer following link where author has explained that how you can implement cancellable commands: 您可以在作者解释了如何实现可取消命令的地方参考以下链接:

http://www.codeproject.com/Articles/274982/Commands-in-MVVM#hdiw1 http://www.codeproject.com/Articles/274982/Commands-in-MVVM#hdiw1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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