2017-07-26 89 views
0

我有一个按钮附加到视图模型中的命令。此按钮删除当前在列表视图中选择的行,所以我想在继续之前显示确认消息框。用户单击确定按钮(在消息框中),然后执行命令,否则,如果用户单击取消按钮命令附加没有被调用。可能吗?如果是这样如何?MVVM显示确认消息框,然后执行附加到按钮的命令

<Button Name="btnDelete" Command="{Binding DeleteRowsCommand}"/> 

另一种可能性是调用点击中通过属性视图模型附加到放置在视图中的自定义消息框的命令,让这个自定义的消息框可见当属性的值是true 。但是,我怎样才能发回视图模型哪个按钮'好'或'取消'已被按下?

+0

您的方法乏味但不好。尝试一些消息框 – Ramankingdom

+0

在'Click'的eventHandler中使用'MessageBox',然后使用ViewModel中的Command并像vm.DeleteRowsCommand.Execute(someObjectIfYouNeedIt)那样执行它。 – XAMlMAX

回答

1

只需用一个MessageBox

在其路由到DeleteRowsCommand使用这种

var result = MessageBox.Show("message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question); 

if (result == MessageBoxResult.Yes) 
{ 
    //your logic 
} 

看一看MessageBox Class更多信息的方法。

+3

这会将PresentationFramework.dll添加到ViewModel程序集,我们不想知道关于VM中的Views的任何信息。 – XAMlMAX

+0

@XAMlMAX是的,这将显示从视图模型'MessageBox',是的,我没有看到任何问题。在视图模型中没有提高'MessageBox'还有其他几种方法,但说实话:不要使用大锤来打破坚果。如果你想用'MessageBox'测试代码,你应该把这段代码放在一个带有接口的类中,以便在测试中模拟它。 –

+0

使用事件处理程序进行Click事件以显示“MessageBox”不一定意味着使用大锤来破解螺母。 – XAMlMAX

0

这样做的一种可能(也是我认为最干净的)方法是实现像DialogService这样的服务,将其注入ViewModel并在命令执行时调用它。通过这样做,您可以将视图和应用程序逻辑分开,以便ViewModel完全不知道实际显示对话的方式,并将所有工作委托给该服务。这是一个例子。

首先创建一个对话框的服务,负责显示对话框,并返回其结果的所有工作:

public interface IDialogService 
{ 
    bool ConfirmDialog(string message); 
} 

public bool ConfirmDialog(string message) 
{ 
    MessageBoxResult result = MessageBox.Show(message, "Confirm", MessageBoxButton.YesNo, MessageBoxImage.Question); 
    return result == MessageBoxResult.Yes ? true : false; 
} 

然后你让你的视图模型依赖于服务和inject它在视图模型:

public class MyViewModel : ViewModelBase 
{ 
    private readonly IDialogService _dialogService; 

    public MyViewModel(IDialogService dialogService) 
    { 
     _dialogService = dialogService; 
    } 
} 

最后,在您的命令中,您可以在命令中调用服务以检查用户是否确定要删除记录:

public Command DeleteRecordsCommand 
{ 
    get 
    { 
     if (_deleteRecordsCommand == null) 
     { 
      _deleteRecordsCommand = new Command(
       () => 
       { 
        if (_dialogService.ConfirmDialog("Delete records?")) 
        { 
         // delete records 
        } 
       } 
      ); 
     } 

     return _deleteRecordsCommand; 
    } 
}