确认窗口在MVVM设计模式中

时间:2015-08-06 08:18:27

标签: c# wpf mvvm

您好我想在点击按钮时显示确认窗口。 我正在尝试开发使用MVVM设计模式我已经实现了它,但我不认为在viewModel中调用视图 是这样做的正确方法。我已附上此代码,请通过它是否正确

<Window x:Class="MessegeBox_Demo_2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button Content="Ckick ME" HorizontalAlignment="Left" 
                    Command="{Binding GetMessegeboxCommand}"
                    Margin="200,131,0,0" VerticalAlignment="Top" Width="75"/>

        </Grid>
    </Window>

public class MainWindowViewModel : ViewModelBaseClass
{
   private ICommand _getMessegeboxCommand;
   public ICommand GetMessegeboxCommand
   {
      get
      {
          return _getMessegeboxCommand ?? (_getMessegeboxCommand = new MessegeBox_Demo_2.Command.realyCommand(() => ShowUsercontrol(), true));
      }
   }
   private void ShowUsercontrol()
   {
      MessegeBox_Demo_2.View.Window1 mbox = new View.Window1();
      mbox.ShowDialog();
   }
}

5 个答案:

答案 0 :(得分:4)

最简单的方法是实现一个对话服务并使用依赖注入将服务注入到viewmodel中。可以对接口具有依赖性,但不依赖于具体实现 以下是我使用的界面:

namespace DialogServiceInterfaceLibrary
{
    public enum MessageBoxButton  
    {
    // Summary:
    //     The message box displays an OK button.
    OK = 0,
    //
    // Summary:
    //     The message box displays OK and Cancel buttons.
    OKCancel = 1,
    //
    // Summary:
    //     The message box displays Yes, No, and Cancel buttons.
    YesNoCancel = 3,
    //
    // Summary:
    //     The message box displays Yes and No buttons.
    YesNo = 4,
    }

    public enum MessageBoxResult
    {
    // Summary:
    //     The message box returns no result.
    None = 0,
    //
    // Summary:
    //     The result value of the message box is OK.
    OK = 1,
    //
    // Summary:
    //     The result value of the message box is Cancel.
    Cancel = 2,
    //
    // Summary:
    //     The result value of the message box is Yes.
    Yes = 6,
    //
    // Summary:
    //     The result value of the message box is No.
    No = 7,
    }

    // Summary:
    //     Specifies the icon that is displayed by a message box.
    public enum MessageBoxIcon
    {
    // Summary:
    //     No icon is displayed.
    None = 0,
    //
    // Summary:
    //     The message box contains a symbol consisting of white X in a circle with
    //     a red background.
    Error = 16,
    //
    // Summary:
    //     The message box contains a symbol consisting of a white X in a circle with
    //     a red background.
    Hand = 16,
    //
    // Summary:
    //     The message box contains a symbol consisting of white X in a circle with
    //     a red background.
    Stop = 16,
    //
    // Summary:
    //     The message box contains a symbol consisting of a question mark in a circle.
    Question = 32,
    //
    // Summary:
    //     The message box contains a symbol consisting of an exclamation point in a
    //     triangle with a yellow background.
    Exclamation = 48,
    //
    // Summary:
    //     The message box contains a symbol consisting of an exclamation point in a
    //     triangle with a yellow background.
    Warning = 48,
    //
    // Summary:
    //     The message box contains a symbol consisting of a lowercase letter i in a
    //     circle.
    Information = 64,
    //
    // Summary:
    //     The message box contains a symbol consisting of a lowercase letter i in a
    //     circle.
    Asterisk = 64,
    }

    public interface IDialogService
    {
        bool OpenFileDialog(bool checkFileExists,string Filter, out string FileName);
        void OpenGenericDialog(object Context,IRegionManager RegionManager);
    MessageBoxResult ShowMessageBox(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon);
    }

实施:

public class DialogService : IDialogService
{
    public bool OpenFileDialog(bool checkFileExists, string Filter, out string FileName) 
    {
        FileName = ""; 
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = false;
        //openFileDialog.Filter = "All Image Files | *.jpg;*.png | All files | *.*";
        openFileDialog.Filter = Filter;
        openFileDialog.CheckFileExists = checkFileExists;
        bool result = ((bool)openFileDialog.ShowDialog());
        if (result)
        {
            FileName = openFileDialog.FileName;
        }
        return result;
    }


    public void OpenGenericDialog(object Context,IRegionManager RegionManager)
    {
        GenericDialogWindow dlg = new GenericDialogWindow(Context,RegionManager);
        dlg.Owner = System.Windows.Application.Current.MainWindow;
        dlg.Show();
    }

    public MessageBoxResult ShowMessageBox(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon)
    {
        return (DialogServiceInterfaceLibrary.MessageBoxResult)System.Windows.MessageBox.Show(message, caption, 
            (System.Windows.MessageBoxButton)buttons,
            (System.Windows.MessageBoxImage)icon);
    }
}

然后将IDialogservice注入viewmodel。 接口和具体实现通常在不同的程序集中

MainWindowViewModel(IDialogService dialogservice){
    _dialogservice = dialogservice;
}

private void ShowUsercontrol()
{
   _dialogservice.ShowMessageBox(... //you get what i mean ;-)
}

对话服务能够打开标准窗口对话框,如文件打开对话框。通用版本也可以使用,但是你需要了解更复杂的棱镜。 Prism还允许使用交互请求从视图模型传递到视图。我更喜欢那种在棱镜上工作的方式,但如果你不知道棱镜会忘记那句话。对于简单的确认窗口来说,它可能太复杂了。像这样简单的对话服务非常适合简单的确认窗口。

通过viewmodel的构造函数注入依赖项,使您已经朝着使用Inversion of control容器的正确方向移动。并且允许更容易的单元测试,因为您可以模拟注入的接口以检查它们是否被正确调用等等。

答案 1 :(得分:1)

  • DialogService方法在此方案中比消息传递机制更合适。它更简洁,更易于编写,更易于编写,更易于理解,您不需要任何第三方框架等。

  • 提示:Depedency注入很好,但是你通常需要很多服务,比如NavigationServiceDialogServiceNotificationService等,如果你需要注入他们对很多视图模型,ctors大,无聊,重复相同的注射等。而不是依赖注入你可以使用任何其他&#34;可测试&#34;方法

由于DialogService在所有视图模型中都是相同的,因此您不必为每个视图模型注入它,但您可以使用某种AppContext类或服务定位器。

ViewModelBase类的示例:

public class ViewModelBase : BindableBase
{
      public virtual IDialogService DialogService 
      { 
         get { return AppContext.Current.DialogService; } 
      }
}

具体的viewmodel示例:

public class HomePageViewModel : ViewModelBase
{
      ...

      public void Cancel_CommandExecute()
      { 
         var dlgResult = DialogService.ShowMessageBox("Do you really want to discard unsaved changes?", "Confirm Exit", DialogButtons.YesNo);
         if (dlgResult != MessageBoxResult.Yes) return;
      }
}

对话服务:

public interface IDialogService
{
    MessageBoxResult ShowMessageBox(string messageBoxText, string caption = null, MessageBoxButton buttons = MessageBoxButton.OK, MessageBoxImage icon = MessageBoxImage.None, MessageBoxResult defaultResult = MessageBoxResult.None);
}

public class DialogService : IDialogService
{
    public virtual MessageBoxResult ShowMessageBox(string messageBoxText, string caption = null, MessageBoxButton buttons = MessageBoxButton.OK, MessageBoxImage icon = MessageBoxImage.None, MessageBoxResult defaultResult = MessageBoxResult.None)
    { 
       return MessageBox.Show(messageBoxText, caption, buttons, icon, defaultResult);
    }
}

在测试中,您可以模拟AppContext.Current,也可以覆盖ViewModelBase.DialogService属性。

也许这不是嘲弄DialogService最干净的方式,但它是一种务实的方法。它使您的viewmodels代码更清晰,更具可读性和可维护性,因为您在每个视图模型中都没有注入和存储DialogService实例。您的视图模型仍然与视图,可测试,可混合等分离。

答案 2 :(得分:1)

您可以在后面的代码中定义和填充Binding。由于代码隐藏是View的一部分,因此调用Messagebox并不会破坏MVVM模式。这样,您可以在设置Binding的值之前显示确认对话框。

代码背后需要的代码是:

public partial class MainWindow : Window
{
    private DependencyProperty myDP;

    public MainWindow()
    {
        ...
        Binding myBinding = new Binding();
        myBinding.Path = new PropertyPath("myValue"); //myValue is a variable in ViewModel
        myBinding.Source = DataContext;
        myDP = DependencyProperty.Register("myValue", typeof(/*class or primitive type*/), typeof(MainWindow));
        BindingOperations.SetBinding(this, myDP, myBinding);
        ...
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBoxResult result = MessageBox.Show("Do you really want to do that?", "", MessageBoxButton.YesNo);
        if (result == MessageBoxResult.Yes
        {
            SetValue(myDP, /*value*/); //this sets the Binding value. myValue in ViewModel is set
        }
    }
}

要在单击按钮时调用Button_Click - 方法,请添加

Click="Button_Click"

到按钮的XAML定义。

答案 3 :(得分:0)

如果你想坚持使用MVVM模式,你不应该(从不)在视图模型中调用UI方法。

从ViewModel打开/关闭窗口的正确方法是使用MVVMLight的Messanger或Prism的EventAggregator向View发送消息。

EventAggregator允许您的ViewModel将消息发送到订阅者列表。订阅特定消息时,附加要执行的函数。

我知道您正在学习此模式的机制,因此您可以编写自己的EventAggregator代码并使用它。

答案 4 :(得分:0)

我已经使用MVVM Light消息传递。 PRISM库也提供了一种很好的方法。

为了处理从视图模型触发的交互以及视图中控件触发的交互,Prism库提供了InteractionRequests和InteractionRequestTriggers,以及自定义的InvokeCommandAction操作。 InvokeCommandAction用于将包含事件的触发器连接到WPF命令。

在ViewModel中创建InteractionRequest属性:

public InteractionRequest<IConfirmation> ConfirmationRequest { get; private set; }

像这样调用交互:

private void RaiseConfirmation()
{
    this.ConfirmationRequest.Raise(
        new Confirmation { Content = "Confirmation Message", Title = "Confirmation" },
        c => { InteractionResultMessage = c.Confirmed ? "The user accepted." : "The user cancelled."; });
}

要使用交互请求,您需要在视图的XAML代码中定义相应的InteractionRequestTrigger:

<prism:InteractionRequestTrigger SourceObject="{Binding ConfirmationRequest, Mode=OneWay}">
    <prism:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True"/>
</prism:InteractionRequestTrigger>

请参阅Interactivity QuickStart Using the Prism Library 5.0 for WPF