Good or bad practice for Dialogs in wpf with MVVM?

前端 未结 3 1717
孤城傲影
孤城傲影 2020-11-22 03:54

I lately had the problem of creating add and edit dialogs for my wpf app.

All I want to do in my code was something like this. (I mostly use viewmodel first approach

3条回答
  •  太阳男子
    2020-11-22 04:51

    If you are talking about dialogue windows and not just about the pop-up message boxes, please consider my approach below. The key points are:

    1. I pass a reference to Module Controller into the constructor of each ViewModel (you can use injection).
    2. That Module Controller has public/internal methods for creating dialogue windows (just creating, without returning a result). Hence to open a dialogue window in ViewModel I write: controller.OpenDialogEntity(bla, bla...)
    3. Each dialogue window notifies about its result (like OK, Save, Cancel, etc.) via Weak Events. If you use PRISM, then it's easier to publish notifications using this EventAggregator.
    4. To handle dialogue results, I'm using subscription to notifications (again Weak Events and EventAggregator in case of PRISM). To reduce dependency on such notifications, use independent classes with standard notifications.

    Pros:

    • Less code. I don't mind using interfaces, but I've seen too many projects where excessiveness of using interfaces and abstraction layers cause more trouble than help.
    • Open dialogue windows through Module Controller is a simple way to avoid strong references and still allows to use mock-ups for testing.
    • Notification through weak events reduce number of potential memory leaks.

    Cons:

    • Not easy to distinguish required notification from others in the handler. Two solutions:
      • send a unique token on opening a dialogue window and check that token in the subscription
      • use generic notification classes where T is enumeration of entities (or for simplicity it can be type of ViewModel).
    • For a project should be an agreement about using notification classes to prevent duplicating them.
    • For enormously large projects the Module Controller can be overwhelmed by methods for creating windows. In this case it's better to split it up in several modules.

    P.S. I have been using this approach for quite a long time now and ready to defend its eligibility in comments and provide some examples if required.

提交回复
热议问题