C# MVVM设计模式中的确认窗口

C# MVVM设计模式中的确认窗口,c#,wpf,mvvm,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.

嗨,我想在点击按钮时显示确认窗口。 我正在尝试使用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();
   }
}

公共类MainWindowViewModel:ViewModelBaseClass
{
专用ICommand_getMessegeboxCommand;
公共ICommand GetMessegeboxCommand
{
得到
{
返回"getMessegeboxCommand??"("getMessegeboxCommand=new-MessegeBox"Demo"2.Command.realyCommand(()=>ShowUsercontrol(),true));
}
}
私有void ShowUsercontrol()
{
MessegeBox_Demo_2.View.Window1 mbox=新视图.Window1();
mbox.ShowDialog();
}
}

最简单的方法是实现dialogservice并使用依赖项注入将服务注入到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 ;-)
}
dialogservice能够像文件打开对话框一样打开标准windows对话框。通用版本也可以使用,但是您需要了解更复杂的prism。 Prism还允许使用交互请求从viewmodel到视图进行通信。我更喜欢在prism中使用这种方式,但如果您不了解prism,请忘记这句话。对于一个简单的确认窗口来说,它可能太复杂了。像这样简单的dialogservice非常适合于一个简单的确认窗口

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

如果您想坚持MVVM模式,就不应该(永远)在视图模型内调用UI方法

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

EventAggregator允许ViewModel向订阅者列表发送消息。当您订阅特定消息时,您会附加一个要执行的函数


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

我已经为此使用了MVVM Light messaging。PRISM库也提供了一种很好的方法

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

在ViewModel中创建InteractionRequest属性:

public InteractionRequest<IConfirmation> ConfirmationRequest { get; private set; }
要使用交互请求,您需要在视图的XAML代码中定义相应的InteractionRequestTrigger:

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

参见

  • DialogService方法比消息传递机制更适合这种情况。它更直观、更易于调试、更易于编写、更易于理解,您不需要任何第三方框架等

  • 提示:依赖项注入很好,但是通常需要相当多的服务,如
    NavigationService
    DialogService
    NotificationService
    ,等等,如果需要将它们注入到许多视图模型中,则这些构件会变得很大,很无聊,重复相同的注入等,而不是依赖注入,您可以使用任何其他“可测试”的方法

由于DialogService在所有viewmodel中都是相同的,因此不必将其注入每个viewmodel,但可以使用某种AppContext类或服务定位器

ViewModelBase类的示例:

public class ViewModelBase : BindableBase
{
      public virtual IDialogService DialogService 
      { 
         get { return AppContext.Current.DialogService; } 
      }
}
混凝土视图模型示例:

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代码更干净、更可读和可维护,因为您没有在每个viewmodel中插入和存储
DialogService
实例。您的视图模型仍然与视图、可测试、可混合等分离。

您可以在代码隐藏中定义和填充绑定。因为代码隐藏是视图的一部分,所以在其中调用Messagebox并不会破坏MVVM模式。这样,可以在设置绑定值之前显示确认对话框

代码隐藏中需要的代码是:

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
        }
    }
}
要在单击按钮时调用
按钮,请添加

Click="Button_Click"

到按钮的XAML定义。

您可以实现打开对话框的方法,也可以使用以MVVM方式实现关注点的清晰分离。关于如何显示新视图(例如对话框窗口)以响应ViewModel事件,这里有几个问题。你已经做的很好,只要它有效。从纯粹的视图来看,您可以考虑使用DependencyProperties为视图提供一种机制,用于检测ViewModel是否需要一个确认窗口,而无需VeiwModel直接调用视图。您不需要事件机制来显示确认对话框。Prism有不同的机制:InteractionRequests。感谢您的帮助,我是否需要根据您的要求为此添加任何外部DLL。如果您想严格要求,接口和实现都有一个单独的程序集。你需要参考
Click="Button_Click"