Re: MVVM Questions

180 views
Skip to first unread message

Michael Sync

unread,
Feb 3, 2010, 11:38:26 AM2/3/10
to John Gossman, wpf-di...@googlegroups.com
Thanks a lot, John. I'm really appreciate it. 

What about if you and our WPF/Silverlight community create a standard for MVVM pattern? I understand that there are a lot of way to implement MVVM but at least, there are some obvious rules that everyone can follow so everyone has same understanding about that pattern. 

Here are some of my thoughts. 

Goals
  • Testabiltiy ( ViewModel is easier to unit test than code-behind or event driven code)
  • Clear seperation between UX designer and developer
  • Increases the "Blendability" of your view
  • Model never needs to be changed to support changes to the view
  • ViewModel rarely needs to be changed to support changes to the view
  • No duplicated code to update views
Do and Don't in View

  • shouldn't contain any logic that you want to test : As Glenn said that MVVM is not code counting exercise, we can write code in code-behind. But you should never write any logic that you want to test. For example: If user select a country then you want to display the list of states or city in your view. This is the business requirement so you should have unit test to test this logic. So, you shouldn't write it in code-behind. 
  • can be a user control or Data Template
  • Keep the view as simple as possible. : We can still use Data Trigger or Value Converter or Visual State or Blend Behivor in XAML with care. 
  • use attached property if something is not bindable : There is one common mistake about PasswordBox. We all knows that WPF Password is not bindable due to the security reason. But if you are having a string property "Password" in Model then it won't be secure no matter whether you set it from code-behind or attached property.
Do and Don't in ViewModel

  • An abstraction of View
  • Connector between View and Model
  • Keep View State, Value Conversion
  • No strong or weak (via Interface) reference of View
  • Make VM as testable as possible (e.g. no call to Singleton class)
  • No Control related Stuff in VM ( Because if you are changing the view then you will have to change VM as well. )
Model 
  • can be Data Model, DTO, POCO, auto-generated proxy of domain class and UI Model based on how you want to have the separation between Domain Service and Presentation Layer
  • No reference to ViewModel
Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


On Wed, Feb 3, 2010 at 11:56 PM, John Gossman <gossm...@gmail.com> wrote:


On Tue, Feb 2, 2010 at 11:13 PM, Michael Sync <mchl...@gmail.com> wrote:
Hi John,

Thanks for creating MVVM pattern. :) 
To be clear...I didn't actually create it, I learned it from some Smalltalk devs and figured out how to use it with WPF...but you're welcome.  :-)

>>1)  efficiently write rich UI 

I agree that we can use MVVM to write rich UI efficiently. But I don't think that MVVM is the only way to write rich UI efficiently. There are a lot of patterns that we can write rich UI ( UI  is not just WPF/Silverlight)
I didn't say it was the only way.  All I said was one of the goals of MVVM was to write UI efficiently.
 

>>2)  where the code is maintainable

The same goes for this as well. Writing maintainable code is not just about MVVM. 

>>3) the model never needs to be changed to support changes to the view
>>4) the viewmodel rarely if ever needs to be changed to support changes to the view
>>5)  there can be many views of the same viewmodel 

Agreed. 

>>6)  the design is as toolable as possible.  

Do you agree the fact that we need to dump the view as much as possible? 
If by "dump" you mean write as little code as possible in the view, I don't think that is a goal.  It *may* be part of the solution, but I think the real thing is to only have code in the view that actually has to do with the view.  Animation code may be huge, but as long as it doesn't include business logic it is fine in the view.
 

Do you think that using Data Trigger or Value Converter are anti-MVVM?  If yes then what about using Visual State Manager, Blend Behivor, Event or Property Trigger? 
On the contrary, all those things were created to support the MVVM pattern. 
 

Is it okay to have control-related stuffs (like Control Event or etc ) in View Model? 
No.  Then you can't switch what Control (a view thing) you use without modifying the ViewModel.
 

I'd love to hear other's opinion as well for those questions..... 

Regards,
Michael Sync




Don't go the way life takes you.
Take life the way you go

http://michaelsync.net



On Tue, Feb 2, 2010 at 3:09 AM, John Gossman <gossm...@gmail.com> wrote:
I haven't written anything about MVVM in a while because there is so much material already being published.  However I have been thinking about what we can do in the platform to make things better and reading a lot of the public stuff, so I thought I'd summarize for my own sake if nothing else:

The state of MVVM reminds me of Peter Naur's classic paper "Programming as Theory Building".  He basically says the proper model for computer programming is not engineering but scientific development where you have problem, you develop a hypothesis for how to fix it, you experiment (write code and test it), and then you decide whether you've solved the problem.  If not you synthesize a new hypothesis and try again. 

MVVM feels more like "science" than anything else I've seen...with lots of authors publishing papers containing their hypotheses and results and suggesting avenues for further research.  Some papers are better than others, some are revolutionary and some contain nothing new.

Fundamentally I think the goal of MVVM has still not been clearly stated.  I posit some of the goals include:
1)  efficiently write rich UI
2)  where the code is maintainable
3) the model never needs to be changed to support changes to the view
4) the viewmodel rarely if ever needs to be changed to support changes to the view
5)  there can be many views of the same viewmodel
6)  the design is as toolable as possible. 

To my mind #6 is the most important and perhaps the one we still have made the least progress with.  Blend Behaviors are a huge step in the right direction, but we need to go further.

I don't think eliminating all code from the View is part of the goal, though it obviously makes some of the others easier.  When it makes them harder though, one should write view code (though whether that means the code behind model or something else is not clear).

Among the next steps,  I would like to eliminate the boilerplate code for INotifyPropertyChanged (and eventually eliminate DependencyProperties and DependencyObjects and allow any property on any class to support binding and change notification).  Further I would like to bind events in the View directly to Commands on the ViewModel so you can say <Button Click="{Binding SaveCommand}" MouseRightButtonUp="{Binding ShowContextCommand}"/>.  This leads to the question whether ICommand itself is just boilerplate and we can simply remove it with binding directly to methods.  The downside being it isn't clear all methods can/should be called from the View in which case it may be useful to have  contract (currently offered by the list of properties of type ICommand).  On the tooling side I would like to see a UI where you can select a control, see a list of the events it supports and choose which methods on the ViewModel you want them to trigger.  This leads in turn to how to handle event arguments like keys.  Keybinding is already pretty good, but the syntax should be simple.




Bill Kempf

unread,
Feb 3, 2010, 12:15:19 PM2/3/10
to wpf-di...@googlegroups.com
On Wed, Feb 3, 2010 at 11:38 AM, Michael Sync <mchl...@gmail.com> wrote:
> Do and Don't in View
>
> shouldn't contain any logic that you want to test : As Glenn said that MVVM
> is not code counting exercise, we can write code in code-behind. But you
> should never write any logic that you want to test. For example: If user
> select a country then you want to display the list of states or city in your
> view. This is the business requirement so you should have unit test to test
> this logic. So, you shouldn't write it in code-behind.

This is a wonderful description of the requirement. Fully on board.
From a personal POV, I like to go a little further, not for a
developer/architectural reason, but because I want the View to be as
nearly entirely in the realm of the designer as possible, and the
designer shouldn't be writing code. But that's not really a
goal/requirement of MVVM.

> can be a user control or Data Template

Or custom control ;). Sorry, I know you meant this, but saying "user
control" instead of just "control" rubbed me wrong.

> Keep the view as simple as possible. : We can still use Data Trigger or
> Value Converter or Visual State or Blend Behivor in XAML with care.

I'm not sure I understand this. It doesn't seem to be related to MVVM
and I don't know what you mean by "with care".

> use attached property if something is not bindable : There is one common
> mistake about PasswordBox. We all knows that WPF Password is not bindable
> due to the security reason. But if you are having a string property
> "Password" in Model then it won't be secure no matter whether you set it
> from code-behind or attached property.

This seems like an implementation detail and not a goal/requirement.
Also, while I don't really understand why PasswordBox's design makes
it "secure", I can't agree that having a property in the Model makes
anything insecure. Your model could just as easily use a SecureString
making it "secure". Then all that's in question is how you move the
password from the PasswordBox to the Model in a secure fashion, and
that can certainly be accomplished in various ways, such as using a
service. Heck, it could probably even be done using the attached
behavior approach. I'd suggest you drop this from the list.

> Do and Don't in ViewModel
>
> An abstraction of View

That's the definition of the pattern, right? Not sure you need to call
it out in a do/don't list.

> Connector between View and Model

Possible between View and Models.

> Keep View State, Value Conversion

Value conversion need not go in the ViewModel, so you should be
careful in how this is worded.

> No strong or weak (via Interface) reference of View

I simply can't agree with this. At all. There's no benefit in forcing
this, and in fact there's a lot of benefits in maintaining a "weak
reference" (wrong term, but it's what you used) to the View.

> Make VM as testable as possible (e.g. no call to Singleton class)

The Singleton pattern must die! If for no other reason than the
confusion it brings to discussions like this. IoC containers have the
concept of a singleton, but they are obtained through dependency
injection instead of through calls to static methods. That's what you
really meant by Singleton here, is you shouldn't have a dependency on
static methods/properties.

> No Control related Stuff in VM ( Because if you are changing the view then
> you will have to change VM as well. )

Depends on what you mean by "control related". You absolutely should
not have any hard dependencies on a control, but looser dependencies
may be necessary. For instance, being able to change the focus may be
a necessary part of the "business logic" of the View, and you'll need
to be able to do that in the ViewModel. There's ways to do this in an
abstract fashion that does not create hard dependencies between the
ViewModel and any particular View. This is fine. Kind of like with the
"no reference to the View" item above, it's really only important that
you need create hard dependencies.

> Model
>
> can be Data Model, DTO, POCO, auto-generated proxy of domain class and UI
> Model based on how you want to have the separation between Domain Service
> and Presentation Layer
> No reference to ViewModel

--
Quidquid latine dictum sit, altum sonatur.
- Whatever is said in Latin sounds profound.

War is peace. Freedom is slavery. Bugs are features.

Michael Sync

unread,
Feb 3, 2010, 12:55:20 PM2/3/10
to wpf-di...@googlegroups.com
Thanks, Bill. 

>> that's not really a goal/requirement of MVVM.

Testability is one of the goals of MVVM, right? So, having business logic in View is not good idea. So, I was suggesting that we should not put any logic that we want to test in codebehind. 

>>control" instead of just "control" rubbed me wrong.

Yeah. Thanks. :) 

>>I'm not sure I understand this. It doesn't seem to be related to MVVM and I don't know what you mean by "with care".

We used to argue that using Data Trigger in View is not good idea because it allows us to write the logic in View. 

>>I'm not sure I understand this. It doesn't seem to be related to MVVM
>>Value conversion need not go in the ViewModel, so you should be careful in how this is worded.

Im refering Justin's Value Converter Code smell. Let's say you want to show the Country Name. But you have only Country ID in VM so you will use VC to converter ID to Name. The suggestion is that if we like to show the name then just add it in VM instead of using Converter. 

>>>while I don't really understand why PasswordBox's design makes it "secure"

According to WPF team, they don't make Passwod bindable for Security. There are a few discussion about that in WPF forum. 

>> I can't agree that having a property in the Model makes anything insecure

Some people think that using attached property for Password is insecure and they think that you should set it in codebehind. My point is that it doesn't matter whether you use the attached property to bind the model or set it manually from codebehind. As long as the property of Password is a string then it will not be secure anyway. 

Yes. You are right. We should use SecureString in Model and we can even use SecureString in attached property. yeah.. It should not be in the list. 

>>> Not sure you need to callit out in a do/don't list.

Yes. Agreed. 


>>I simply can't agree with this. At all. There's no benefit in forcing this, and 

>>in fact there's a lot of benefits in maintaining a "weak reference" (wrong term, but it's what you used) to the View.

I dont think it's wrong term. What I meant by "weak" is not .NET WeakReference. I saw people using it like that in forum. Anyway, I'm not a native English speaker so you can suggest me what I should call that one. 

Could you please give me some example of having IVew in VM? Would it be like MVP pattern? 

Thanks for your inputs. I really appreciate it... I think that it will help us to understand more about MVVM and we can have same understanding as well.. Otherwise, people will say that My "MVVM" is totally different from your MVVM.. :) 

Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Bill Kempf

unread,
Feb 3, 2010, 1:29:37 PM2/3/10
to wpf-di...@googlegroups.com
On Wed, Feb 3, 2010 at 12:55 PM, Michael Sync <mchl...@gmail.com> wrote:
> Thanks, Bill.
>>> that's not really a goal/requirement of MVVM.
> Testability is one of the goals of MVVM, right? So, having business logic in
> View is not good idea. So, I was suggesting that we should not put any logic
> that we want to test in codebehind.

That's taken out of context, and you misunderstood me. "That's not
really a goal/requirement of MVVM" wasn't in reference to your stated
goal, but to my extended goal of eliminating code behind for the sake
of less designer friction.

>>>I'm not sure I understand this. It doesn't seem to be related to MVVM and
>>> I don't know what you mean by "with care".
> We used to argue that using Data Trigger in View is not good idea because it
> allows us to write the logic in View.

That sort of argument always bothers me. When something "allows you"
to do something, it's not the same as requiring or even encouraging
you to do it. The bad idea is putting business logic in the View, and
I can write plenty of data triggers that don't do that.

>>>I'm not sure I understand this. It doesn't seem to be related to MVVM
>>>Value conversion need not go in the ViewModel, so you should be careful in
>>> how this is worded.
> Im refering Justin's Value Converter Code smell. Let's say you want to show
> the Country Name. But you have only Country ID in VM so you will use VC to
> converter ID to Name. The suggestion is that if we like to show the name
> then just add it in VM instead of using Converter.

Yeah, and that idea is controversial. Me, I'd rather use a converter
if this is going to be done frequently. Does a much better job of
keeping things DRY this way. More importantly, there's a lot of value
converters that simply do NOT belong in the ViewModel, ever. Things
like a SeverityToColorConverter come to mind. This is solely a
presentation concept, and has no place in a ViewModel.

>>>I simply can't agree with this. At all. There's no benefit in
>>> forcing this, and
>>>in fact there's a lot of benefits in maintaining a "weak reference" (wrong
>>> term, but it's what you used) to the View.
> I dont think it's wrong term. What I meant by "weak" is not .NET
> WeakReference. I saw people using it like that in forum. Anyway, I'm not a
> native English speaker so you can suggest me what I should call that one.

Abstract is probably better than weak. And coupling is better than
reference. They mean the same thing in some contexts, but in .NET
languages a reference has a specific meaning, so "weak reference" can
confuse people.

> Could you please give me some example of having IVew in VM? Would it be like
> MVP pattern?

Onyx is heavily based on an IView concept, so you could look there. At
runtime, there's a logical coupling betwen a View and a ViewModel, and
not maintaining a physical reference between them can thus lead to
complications. For instance, if you take a ViewModel first approach,
you have to be careful to maintain a reference to the View somehow,
lest the GC collect the View prematurely.

> Thanks for your inputs. I really appreciate it... I think that it will help
> us to understand more about MVVM and we can have same understanding as
> well.. Otherwise, people will say that My "MVVM" is totally different from
> your MVVM.. :)

To some extent, that's a good thing. MVVM is a pattern. Patterns can
be applied in multiple ways. As long as the pattern is still adhered
to, the differing applications are not really relevant. Things like
"not having any reference to the View from the ViewModel" are not part
of the pattern.

Michael Sync

unread,
Feb 3, 2010, 9:51:46 PM2/3/10
to wpf-di...@googlegroups.com
Hi Bill,

Good Morning! 

Sorry for late reply. 

>>Abstract is probably better than weak. And coupling is better than reference. They mean the same thing in some contexts, but in .NET languages a reference has a specific meaning, so "weak reference" can confuse people.

Thanks, Bill. I will use "Abstract Coupling" instead of "Weak reference (via interface)" in future. 

>>Things like a SeverityToColorConverter come to mind. This is solely a presentation concept, and has no place in a ViewModel.

Yeah. I totally agreed with this. 

>>I can write plenty of data triggers that don't do that

That's why I wanted to say that we can use Data Triggers or Value Converter in View. But we need to be careful not to write the business logic with Data Trigger. Yes. I have seen that people use Data Trigger for some business logic. 

>>Onyx is heavily based on an IView concept, so you could look there

Sure. I'm planning to take a look at all MVVM frameworks. 

Please help me to take a look at the code below. Is it MVP or MVVM? 

interface IView{

 
void ShowMessage(string message);

}

class View : IView {
   
public void ShowMessage(string message){
             
MessageBox.Show(this, message);
   
}
}

class ViewModel{

private IView view;

public ViewModel(IVew view){

 
this.view = view;

}

........

view
.ShowMessage("This is a msg");

}

>>>To some extent, that's a good thing. MVVM is a pattern. Patterns can be applied in multiple ways. As long as the pattern is still adhered to, the differing applications are not really relevant. Things like "not having any reference to the View from the ViewModel" are not part of the pattern.

This is what you believe, right? There are a lot of people who believe that VM should not have any view reference. According to John's class diagram <link>, the 2-ways binding is the only way that we communicate between View and ViewModel. Not via interface. 

I believe that "not having any reference to the View from the ViewModel" can be a part of pattern because we don't want VM to be changed to support the changes of View. 

Actually, pattern has a name. The way of implementing the pattern can be different and we can combine a few patterns together based on our need. But still it has a name. 

Regards,
Michael Sync

Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Bill Kempf

unread,
Feb 4, 2010, 9:24:56 AM2/4/10
to wpf-di...@googlegroups.com
On Wed, Feb 3, 2010 at 9:51 PM, Michael Sync <mchl...@gmail.com> wrote:
> Please help me to take a look at the code below. Is it MVP or MVVM?
>
> interface IView{
>
>
>   void ShowMessage(string message);
>
>
> }
>
>
> class View : IView {
>
>     public void ShowMessage(string message){
>
>               MessageBox.Show(this, message);
>
>     }
>
> }
>
>
> class ViewModel{
>
>
> private IView view;
>
>
> public ViewModel(IVew view){
>
>
>   this.view = view;
>
>
> }
>
> ........
>
>
> view.ShowMessage("This is a msg");
>
>
> }

There's not enough info here to say for sure. It could go either way.
I will say, however, that this is not what I would do. Onyx has an
IDisplayMessage service for this.

>>>>To some extent, that's a good thing. MVVM is a pattern. Patterns can be
>>>> applied in multiple ways. As long as the pattern is still adhered to, the
>>>> differing applications are not really relevant. Things like "not having any
>>>> reference to the View from the ViewModel" are not part of the pattern.
> This is what you believe, right? There are a lot of people who believe that
> VM should not have any view reference. According to John's class diagram
> <link>, the 2-ways binding is the only way that we communicate between View
> and ViewModel. Not via interface.

I don't believe John intended the diagram to explicitly disallow other
forms of communication. For instance, it's readily accepted by most
that EventAggregator is a key part of MVVM, and that certainly allows
for other forms of communication. Regardless, yes, it's my very strong
opinion that there's nothing in the pattern that disallows services,
including a View service, and in fact there are many things that are
difficult to do at, at best, without this.

> I believe that "not having any reference to the View from the ViewModel" can
> be a part of pattern because we don't want VM to be changed to support the
> changes of View.

It's my contention that you don't need to change the ViewModel to
support the View even when using loose coupling.

> Actually, pattern has a name. The way of implementing the pattern can be
> different and we can combine a few patterns together based on our need. But
> still it has a name.

Not just a name, but a definition, and I contend that the definition
doesn't, nor should it, include an exclusion to the use of a view
service.

Shawn Wildermuth

unread,
Feb 4, 2010, 9:48:31 AM2/4/10
to wpf-di...@googlegroups.com
Both these options seems to like more coupling to me. I am doing this via a
Message (usually handled by the Shell or some other service) to show
messages. That way when in test or minimal dev environments, the message
can be sent, but ignored.

Thanks,
Shawn Wildermuth
http://wildermuth.com

Note: This was typed on a big ole laptop so any misspellings and
punctuations are completely my fault…not my phone’s.

Sacha Barber

unread,
Feb 4, 2010, 9:57:10 AM2/4/10
to wpf-di...@googlegroups.com
I would say that is MVP, and I too would do that with a dedicated service, that also has mocks that are DId in in my test cases.
--
Sacha Barber
sacha....@gmail.com

Bill Kempf

unread,
Feb 4, 2010, 10:03:06 AM2/4/10
to wpf-di...@googlegroups.com
Using a service, when in test or minimal dev environments, the service
method can be called, but ignored. You gain nothing by using a
Message, and some things can be complicated to accomplish using
methods.

Sacha Barber

unread,
Feb 4, 2010, 10:21:37 AM2/4/10
to wpf-di...@googlegroups.com
Total agree with Bill here.
--
Sacha Barber
sacha....@gmail.com

Michael Sync

unread,
Feb 4, 2010, 11:11:53 AM2/4/10
to wpf-di...@googlegroups.com
Thanks, Bill, Shawn and Sacha.

>>Onyx has an IDisplayMessage service for this.

We will probably call IDisplayMessageService in CAB,SCSF or Prism, In MVVM, we used to have IDisplayMessageService or IDialogService or etc.

>>a View service

I think you mis-understand me. I'm not talking about IDisplayService or ViewService. I just want to know whether you have an interface for every views (like we have in MVP pattern) or not.

>>I would say that is MVP

Yes, Sacha. I raised the same question in other group as well. The most of people believe that this is a MVP.

As of now, I think we have different thoughts about having the interface of View in ViewModel. But good thing is that we all agree for all facts.

Please discuss if anyone like to add more on that..

Thanks for participating in discussion.. I really appreciate it. Actually, I'm sharing some of my idea about MVVM pattern with my team and Singapore Community. The most of people in my team have the working experience with winform (CAB, SCSF and MVP pattern) so I used to get a lot of questions like that.. there are only a few people who are using MVVM (even WPF or Silverlight) so I don't get much people to discuss in SG. This group is the only one that I can discuss online. Thanks again for your suggestion..  :)

Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Bill Kempf

unread,
Feb 4, 2010, 1:23:16 PM2/4/10
to wpf-di...@googlegroups.com
On Thu, Feb 4, 2010 at 11:11 AM, Michael Sync <mchl...@gmail.com> wrote:
> Thanks, Bill, Shawn and Sacha.
>
>>>Onyx has an IDisplayMessage service for this.
>
> We will probably call IDisplayMessageService in CAB,SCSF or Prism, In MVVM,
> we used to have IDisplayMessageService or IDialogService or etc.

Same concept, different name. It's a service whether you call it one
in the name or not.

>>>a View service
>
> I think you mis-understand me. I'm not talking about IDisplayService or
> ViewService. I just want to know whether you have an interface for every
> views (like we have in MVP pattern) or not.

Onyx has an IView for every view, yes. IView is a service. It's main
purpose is to provide access to other services (it's an
IServiceProvider), but it does contain a property called ViewElement
that's the actual UIElement of the view. It's also probably going to
be gaining Show and Close methods in V2 of the framework. I've gone
back and forth on whether or not the ViewElement should be included,
because frankly anything you'd do with it could be accomplished with
out it using the IServiceProvider, but I have used it once or twice
for convenience (and in a manner that was testable and didn't couple
me to the specific view instance or implementation). I'll agree that
this is controversial, at best, but I'm pragmatic not dogmatic.

>>>I would say that is MVP
>
> Yes, Sacha. I raised the same question in other group as well. The most of
> people believe that this is a MVP.

Why? I don't think you can tell from what little was posted, but I'd
love to hear the reasoning.

Michael D. Brown

unread,
Feb 4, 2010, 1:22:53 PM2/4/10
to wpf-di...@googlegroups.com

I agree with the good doctor on this. It doesn’t matter if it’s ViewModel or Presenter it’s all poo. In the strictest sense, a viewmodel shouldn’t have a reference to a given view…but that guidance is there because should you need it a ViewModel can be reused with multiple views (you could even go so far as having a ViewModel support multiple UI platforms such as WPF/Silverlight and even ASP.NET MVC). If you don’t need this capability, ignore that guidance and put what you need into the VM. Just don’t go hog wild and consider using interfaces to remove coupling to a SPECIFIC view. Both of these will open options for you in the future to support multiple views and possible even different platforms.

 

From: wpf-di...@googlegroups.com [mailto:wpf-di...@googlegroups.com] On Behalf Of Michael Sync
Sent: Wednesday, February 03, 2010 9:52 PM
To: wpf-di...@googlegroups.com
Subject: Re: [WPF Disciples] Re: MVVM Questions

 

 
interface IView{


 
void ShowMessage(string message);


}


class View : IView {

    public void ShowMessage(string message){

              MessageBox.Show(this, message);

    }

}


class ViewModel{


private IView view;


public ViewModel(IVew view){


 
this.view = view;


}


........


view.
ShowMessage("This is a msg");


}

Daniel Vaughan

unread,
Feb 4, 2010, 6:04:28 PM2/4/10
to WPF Disciples
I try to avoid the ViewModel knowing about the view via an interface
if at all possible, preferring instead loosely coupled eventing (as in
Prisms). I see this a being 'pure' MVVM, and sometimes it may not be
practical.
I’d say that in non-arbitrary projects, the message service is better
implemented as a service, as I think most of us do anyway.


On Feb 3, 5:38 pm, Michael Sync <mchls...@gmail.com> wrote:
> Thanks a lot, John. I'm really appreciate it.
>
> What about if you and our WPF/Silverlight community create a standard for
> MVVM pattern? I understand that there are a lot of way to implement MVVM but
> at least, there are some obvious rules that everyone can follow so everyone
> has same understanding about that pattern.
>
> Here are some of my thoughts.
>

> *Goals*
>
>    -
>    - Testabiltiy ( ViewModel is easier to unit test than code-behind or
>    event driven code)
>    - Clear seperation between UX designer and developer
>    - Increases the "Blendability" of your view
>    - Model never needs to be changed to support changes to the view
>    - ViewModel rarely needs to be changed to support changes to the view
>    - No duplicated code to update views
>
> *Do and Don't in View*
>
>    - *shouldn't contain any logic that you want to test* : As Glenn said


>    that MVVM is not code counting exercise, we can write code in code-behind.
>    But you should never write any logic that you want to test. For example: If
>    user select a country then you want to display the list of states or city in
>    your view. This is the business requirement so you should have unit test to
>    test this logic. So, you shouldn't write it in code-behind.

>    - *can be a user control or Data Template*
>    - *Keep the view as simple as possible. : *We can still use Data Trigger


>    or Value Converter or Visual State or Blend Behivor in XAML with care.

>    - *use attached property if something is not bindable : *There is one


>    common mistake about PasswordBox. We all knows that WPF Password is not
>    bindable due to the security reason. But if you are having a string property
>    "Password" in Model then it won't be secure no matter whether you set it
>    from code-behind or attached property.
>

> *Do and Don't in ViewModel*
>
>    - An abstraction of View
>    - Connector between View and Model
>    - Keep View State, Value Conversion
>    - No strong or weak (via Interface) reference of View
>    - Make VM as testable as possible (e.g. no call to Singleton class)
>    - No Control related Stuff in VM ( Because if you are changing the view


>    then you will have to change VM as well. )
>

> *Model *
>
>    -
>    - can be Data Model, DTO, POCO, auto-generated proxy of domain class and


>    UI Model based on how you want to have the separation between Domain Service
>    and Presentation Layer

>    - No reference to ViewModel


>
> Thanks and Best Regards,
> Michael Sync
>
> Don't go the way life takes you.
> Take life the way you go
>
> http://michaelsync.net
>

> On Wed, Feb 3, 2010 at 11:56 PM, John Gossman <gossmans...@gmail.com> wrote:

Jeremiah Morrill

unread,
Feb 4, 2010, 6:29:25 PM2/4/10
to wpf-di...@googlegroups.com
>>I try to avoid the ViewModel knowing about the view via an interface
if at all possible

+1 Daniel.  Though I try to avoid the event aggregator if the event needs to be published from the View, like in the case of IActiveAware.  In that scenario I might go into a cheaper/lazy MVP style by opening up the IViewModel with an IViewModel.SetActive(...) and storing ref to IViewModel on my IView.SetViewModel(...).

Shawn Wildermuth

unread,
Feb 4, 2010, 6:43:04 PM2/4/10
to wpf-di...@googlegroups.com

Let me be clearer, I use commanding (or a  Behavior) to talk to the VM and the VM can issue the message (a la the Messenger in MVVM Light, or EventAggregator (which is growing too much trouble for me)).

 

Thanks,

Shawn Wildermuth

http://wildermuth.com

 

Note: This was typed on a big ole laptop so any misspellings and punctuations are completely my fault…not my phone’s.

 

From: wpf-di...@googlegroups.com [mailto:wpf-di...@googlegroups.com] On Behalf Of Jeremiah Morrill
Sent: Thursday, February 04, 2010 6:29 PM
To: wpf-di...@googlegroups.com
Subject: Re: [WPF Disciples] Re: MVVM Questions

 

>>I try to avoid the ViewModel knowing about the view via an interface
if at all possible

Daniel Vaughan

unread,
Feb 4, 2010, 6:50:21 PM2/4/10
to WPF Disciples
Jer, do you find the IViewModel.SetActive(...) approach to be useful
where a viewmodel oversees multiple views? I myself, generally go 1 to
1, but that’s just me. I would probably avoid having a means to set
the View using a base interface because it could be overused, but
again it’s a matter of preference.


On Feb 5, 12:29 am, Jeremiah Morrill <jeremiah.morr...@gmail.com>


wrote:
> >>I try to avoid the ViewModel knowing about the view via an interface
>

> if at all possible
>
> +1 Daniel.  Though I try to avoid the *event aggregator* if the event needs


> to be published from the View, like in the case of IActiveAware.  In that
> scenario I might go into a cheaper/lazy MVP style by opening up the
> IViewModel with an IViewModel.SetActive(...) and storing ref to IViewModel
> on my IView.SetViewModel(...).
>

Daniel Vaughan

unread,
Feb 4, 2010, 6:53:42 PM2/4/10
to WPF Disciples
Yes, I forgot to mention commanding. Must be getting late. Cheers
Shawn.


On Feb 5, 12:43 am, "Shawn Wildermuth" <shawn.li...@agilitrain.com>
wrote:


> Let me be clearer, I use commanding (or a  Behavior) to talk to the VM and
> the VM can issue the message (a la the Messenger in MVVM Light, or
> EventAggregator (which is growing too much trouble for me)).
>
> Thanks,
>
> Shawn Wildermuth
>

>  <http://wildermuth.com/>http://wildermuth.com


>
> Note: This was typed on a big ole laptop so any misspellings and

> punctuations are completely my fault.not my phone's.


>
> From: wpf-di...@googlegroups.com [mailto:wpf-di...@googlegroups.com]
> On Behalf Of Jeremiah Morrill
> Sent: Thursday, February 04, 2010 6:29 PM
> To: wpf-di...@googlegroups.com
> Subject: Re: [WPF Disciples] Re: MVVM Questions
>
> >>I try to avoid the ViewModel knowing about the view via an interface
>
> if at all possible
>
> +1 Daniel.  Though I try to avoid the event aggregator if the event needs to
> be published from the View, like in the case of IActiveAware.  In that
> scenario I might go into a cheaper/lazy MVP style by opening up the
> IViewModel with an IViewModel.SetActive(...) and storing ref to IViewModel
> on my IView.SetViewModel(...).
>

Jeremiah Morrill

unread,
Feb 4, 2010, 7:09:46 PM2/4/10
to wpf-di...@googlegroups.com
Totally right..can be overused..which is a problem in it's own.  But for special cases (like IActiveAware, which has to be implemented on your IView class), I find it to be elegant.  So far, I've only had to mix up some MVP and MVVM a few times. 

In my code, the only thing that knows what an IView's concrete type is my IoC container.  My typical IView looks like this:

public interface IView
{
     void SetViewModel(IViewModel viewModel)
}

and my IViewModel:

public interface IViewModel
{
    object View{get;}//read-only
}

and the concrete VM:

public class ViewModel : IViewModel
{
       public ViewModel(IView view)
       {
             view.SetViewModel(this);
             View = view;
       }

       public object View{get;private set;}

}

I would say 9/10 of my V/VM's look almost exactly like this (no extra interface methods, interface properties) and one method.  The view never storing the IViewModel beyond setting the DataContext.  But you see how this method makes it ripe for mixing MVP...and ripe for abuse ;)

-Jer

Shawn Wildermuth

unread,
Feb 4, 2010, 7:28:23 PM2/4/10
to wpf-di...@googlegroups.com

Curious, in your SetViewModel, you’re specifying an interface.  Since I rely heavily on binding, I just accept an object (since the bindings are basically duck-typed).  What are you getting out of the interface?

 

Thanks,

Shawn Wildermuth

http://wildermuth.com

 

Note: This was typed on a big ole laptop so any misspellings and punctuations are completely my fault…not my phone’s.

 

From: wpf-di...@googlegroups.com [mailto:wpf-di...@googlegroups.com] On Behalf Of Jeremiah Morrill
Sent: Thursday, February 04, 2010 7:10 PM
To: wpf-di...@googlegroups.com
Subject: Re: [WPF Disciples] Re: MVVM Questions

 

Totally right..can be overused..which is a problem in it's own.  But for special cases (like IActiveAware, which has to be implemented on your IView class), I find it to be elegant.  So far, I've only had to mix up some MVP and MVVM a few times. 

Daniel Vaughan

unread,
Feb 4, 2010, 7:35:32 PM2/4/10
to WPF Disciples
Another approach might be to make the View property setter on the
ViewModel base implementation internal, and set it using some factory
mechanism. Then the IActiveAware could be fulfilled without exposing
the ViewModel to subclasses. What do you think?


On Feb 5, 1:09 am, Jeremiah Morrill <jeremiah.morr...@gmail.com>
wrote:


> Totally right..can be overused..which is a problem in it's own.  But for
> special cases (like IActiveAware, which has to be implemented on your IView
> class), I find it to be elegant.  So far, I've only had to mix up some MVP
> and MVVM a few times.
>
> In my code, the only thing that knows what an IView's concrete type is my
> IoC container.  My typical IView looks like this:
>
> public interface IView
> {
>      void SetViewModel(IViewModel viewModel)
>
> }
>
> and my IViewModel:
>
> public interface IViewModel
> {
>     object View{get;}//read-only
>
> }
>
> and the concrete VM:
>
> public class ViewModel : IViewModel
> {
>        public ViewModel(IView view)
>        {
>              view.SetViewModel(this);
>              View = view;
>        }
>
>        public object View{get;private set;}
>
> }
>
> I would say 9/10 of my V/VM's look almost exactly like this (no extra
> interface methods, interface properties) and one method.  The view never
> storing the IViewModel beyond setting the DataContext.  But you see how this
> method makes it ripe for mixing MVP...and ripe for abuse ;)
>
> -Jer
>

> ...
>
> read more »

Jeremiah Morrill

unread,
Feb 4, 2010, 7:40:06 PM2/4/10
to wpf-di...@googlegroups.com
I think for almost all usages, an object type would be fine in the SetViewModel(...).  The only advantage I can see, beyond being ready for some MVP sloppiness, is that on the VM ctor, when I run the IView.SetViewModel(this), I get strong-typing on my one-to-one view/viewmodel.  Maybe I just do it out of habit?  ;)

Jeremiah Morrill

unread,
Feb 4, 2010, 8:00:45 PM2/4/10
to wpf-di...@googlegroups.com
Daniel, I'm not sure I follow.  The IView (and VM) are both instantiated by IoC.   IActiveAware is only used by the IRegionManager, but implemented on your view.  I need to let the VM know when the RegionManager sets IActiveAware.IsActive has changed.  So the way I understand my options are I could use a message bus in code-behind, MVP style communication back to the VM in code-behind, or inherit my IView from IActiveAware and hook into the IsActiveChanged event from the VM (which I guess would be the same as MVP style).

-Jer

Glenn Block

unread,
Feb 5, 2010, 3:03:53 AM2/5/10
to wpf-di...@googlegroups.com
I say it 'depends'

Yes you can send a message from the VM to the view. I would definitely
do this if there are multiple views of the same VM.

If however there is a 1 to 1 relationship between the View and VM
(which is very often the case) I say Yagni. It's much more
discoverable, intuitive and more clearly expresses intent to just have
an interface for the view. Then instead of sending a message, I just
directly invoke it.

I am sure several folks will disagree, so I am ready for you to
convince me otherwise :-)

On 2/4/10, Shawn Wildermuth <shawn...@agilitrain.com> wrote:
> Let me be clearer, I use commanding (or a Behavior) to talk to the VM and
> the VM can issue the message (a la the Messenger in MVVM Light, or
> EventAggregator (which is growing too much trouble for me)).
>
>
>
> Thanks,
>
> Shawn Wildermuth
>

> <http://wildermuth.com/> http://wildermuth.com


>
>
>
> Note: This was typed on a big ole laptop so any misspellings and

> punctuations are completely my fault.not my phone's.

--
Sent from my mobile device

Glenn Block

unread,
Feb 5, 2010, 3:09:03 AM2/5/10
to wpf-di...@googlegroups.com
Where is that rule written that 'Thine ViewModel must not reference
thy view'? The pattern of MVVM (which is very similar to
PresentationModel) is all about the encapsulation of the View logic in
the model, and about the View talking to it through binding. It sets
no constraints on how the VM talks back to the biw.

On 2/4/10, Michael D. Brown <mike....@azurecoding.net> wrote:
> I agree with the good doctor on this. It doesn't matter if it's ViewModel or
> Presenter it's all poo. In the strictest sense, a viewmodel shouldn't have a

> reference to a given view.but that guidance is there because should you need

> <link <http://blogs.msdn.com/johngossman/archive/2006/04/13/576163.aspx> >,


> the 2-ways binding is the only way that we communicate between View and
> ViewModel. Not via interface.
>
>
>
> I believe that "not having any reference to the View from the ViewModel" can
> be a part of pattern because we don't want VM to be changed to support the
> changes of View.
>
>
>
> Actually, pattern has a name. The way of implementing the pattern can be
> different and we can combine a few patterns together based on our need. But
> still it has a name.
>
>
>
>
>
>

--

Glenn Block

unread,
Feb 5, 2010, 3:22:52 AM2/5/10
to wpf-di...@googlegroups.com
The difference between MVP and MVVM is very simple, yet we make it so
difficult..

MVP, Views binds to data hanging off of the Presenter, not the
Presenter itself. UI gestures are routed through the presenter via
event handlers on the view which invoke the Presenter.

ViewModel, View binds directly to the ViewModel itself. This possible
because UI gestures can also be handled through binding ie through
commanding.

So the primary difference is the manner in which information and
actions flow from the VM to the View. In MVP it is a combination of
binding and delegation, in MVVM it is purely through.binding.

How the communication is handled from the other side is really
irrelavent as long as these fundamentals are maintained. I see no harm
in having the VM talk to the view if it is warranted.

Corrado Cavalli

unread,
Feb 5, 2010, 3:24:10 AM2/5/10
to wpf-di...@googlegroups.com
At the moment I'm using messages to talk from VM to tied View and I'm quite
happy with that,maybe a little cumbersome to test but it works.
What method you suggest to pass the IView to the ViewModel?, still have to
find one that satisfies me.

.Corrado

-----Original Message-----
From: wpf-di...@googlegroups.com [mailto:wpf-di...@googlegroups.com]
On Behalf Of Glenn Block
Sent: venerdì 5 febbraio 2010 09:09
To: wpf-di...@googlegroups.com
Subject: Re: [WPF Disciples] Re: MVVM Questions

Where is that rule written that 'Thine ViewModel must not reference thy
view'? The pattern of MVVM (which is very similar to
PresentationModel) is all about the encapsulation of the View logic in the
model, and about the View talking to it through binding. It sets no
constraints on how the VM talks back to the biw.

On 2/4/10, Michael D. Brown <mike....@azurecoding.net> wrote:

> I agree with the good doctor on this. It doesn't matter if it's
> ViewModel or Presenter it's all poo. In the strictest sense, a

> viewmodel shouldn't have a reference to a given view.but that guidance

> <http://blogs.msdn.com/johngossman/archive/2006/04/13/576163.aspx> >,

> the 2-ways binding is the only way that we communicate between View and
ViewModel. Not via interface.
>
>
>
> I believe that "not having any reference to the View from the
> ViewModel" can be a part of pattern because we don't want VM to be
> changed to support the changes of View.
>
>
>
> Actually, pattern has a name. The way of implementing the pattern can
> be different and we can combine a few patterns together based on our
> need. But still it has a name.
>
>
>
>
>
>

--

Glenn Block

unread,
Feb 5, 2010, 3:48:44 AM2/5/10
to wpf-di...@googlegroups.com
If I am doing VM first, the View gets injected in the constructor of
the VM. If view first, I would have a SetView method or a property.

The determiner for me on whether to use a view ref is how chatty is
the communication between from the VM back to the view, and how
complex is that communication, For example let's say an action in the
VM needs to initiate displaying a popup which collects some
information that is passed back to to the VM after it closes. I would
find it far less cumbersome to just invoke a method on the View which
gives me a return value. rather than sending a messag to display the
view and subscribing to a return message sent back from the view after
it closed, or checking some prop it updated.

Glenn

Corrado Cavalli

unread,
Feb 5, 2010, 4:20:03 AM2/5/10
to wpf-di...@googlegroups.com
Agree with you about a method being less cumbersome than message, wondering
how cumbersome is to inject an IView into VM via IOC/MEF supporting
Blendability.

.Corrado

-----Original Message-----
From: wpf-di...@googlegroups.com [mailto:wpf-di...@googlegroups.com]
On Behalf Of Glenn Block
Sent: venerdì 5 febbraio 2010 09:49
To: wpf-di...@googlegroups.com
Subject: Re: [WPF Disciples] Re: MVVM Questions

If I am doing VM first, the View gets injected in the constructor of the VM.
If view first, I would have a SetView method or a property.

The determiner for me on whether to use a view ref is how chatty is the
communication between from the VM back to the view, and how complex is that
communication, For example let's say an action in the VM needs to initiate
displaying a popup which collects some information that is passed back to to
the VM after it closes. I would find it far less cumbersome to just invoke a
method on the View which gives me a return value. rather than sending a
messag to display the view and subscribing to a return message sent back
from the view after it closed, or checking some prop it updated.

Glenn

On 2/5/10, Corrado Cavalli <corrado...@gmail.com> wrote:

Glenn Block

unread,
Feb 5, 2010, 4:54:55 AM2/5/10
to wpf-di...@googlegroups.com
For Blend you would have to do it in the load event as the ctors don't fire for the main user control. It should work fine though. You could also write an attached property that would handle passing off the view to the VM by calling it's SetView property.
 
 
Glenn

Sacha Barber

unread,
Feb 5, 2010, 5:05:20 AM2/5/10
to wpf-di...@googlegroups.com
Why not just use an attached DP to create the ViewModel passing in the View to the VM. Marlon has nice example of this.
--
Sacha Barber
sacha....@gmail.com

Glenn Block

unread,
Feb 5, 2010, 5:15:44 AM2/5/10
to wpf-di...@googlegroups.com
That was what I meant when I said attached prop. Though I would still
want the VM to get created by a container so it's dependencies
(services) are injected.

Sacha Barber

unread,
Feb 5, 2010, 5:22:18 AM2/5/10
to wpf-di...@googlegroups.com
Yeah I can see that, though in my Cinch framework, what I do is resolve all the services manually. But I can see the beuty of injecting all of them, via constructor say.
--
Sacha Barber
sacha....@gmail.com

Corrado Cavalli

unread,
Feb 5, 2010, 5:28:11 AM2/5/10
to wpf-di...@googlegroups.com
Yes, i prefer container approach too.

-----Original Message-----
From: wpf-di...@googlegroups.com [mailto:wpf-di...@googlegroups.com]
On Behalf Of Glenn Block
Sent: venerdì 5 febbraio 2010 11:16
To: wpf-di...@googlegroups.com
Subject: Re: [WPF Disciples] Re: MVVM Questions

That was what I meant when I said attached prop. Though I would still want
the VM to get created by a container so it's dependencies
(services) are injected.

On 2/5/10, Sacha Barber <sacha....@gmail.com> wrote:

Michael Sync

unread,
Feb 5, 2010, 6:49:18 AM2/5/10
to wpf-di...@googlegroups.com
Thanks, Glenn... 

Do you think that it's okay to set like iview.SetData or iview.SetSomething from ViewModel? Could you please give me an example for setting view from ViewModel via an interface? 

How does it helpful to set the view from the constructor of View Model? Example please. 

Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Bill Kempf

unread,
Feb 5, 2010, 7:50:41 AM2/5/10
to wpf-di...@googlegroups.com
Even when doing View first, you can inject the IView via the ViewModel
constructor. That's the way the current Onyx works. I'm moving Onyx to
ViewModel first, however, as it solves many problems. The only issue
with ViewModel first is ensuring things remain Blendable, but I'm
working hard on ensuring that as well (d:DataContext and friends to
the rescue!). So, Michael, for an example I again refer you to Onyx.

--

Michael Sync

unread,
Feb 5, 2010, 7:55:32 AM2/5/10
to wpf-di...@googlegroups.com
Hi Glenn,



>>MVP, Views binds to data hanging off of the Presenter, not the Presenter itself. UI gestures are routed through the presenter via event handlers on the view which invoke the Presenter.
>>>ViewModel, View binds directly to the ViewModel itself. This possible because UI gestures can also be handled through binding ie through commanding.

I think this is the flow from View to Presenter. I understand that View and ViewModel are communicated via binding or commanding. The question is that ... Do you set the view from ViewModel via interface like iview.SetSomething() from ViewModel

Let's make it more clear.. I'm sure that it's more clear for all of us to see the code.

Let's create one example: 

--- User can enter First Name and Last Name in UI.
--- User can save the data. 

Here is the MVP patten that I understand

Model 

 public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

Interface of View

  public interface IPersonView
    {
        void SetData(Person person);
    }

View

public partial class PersonView : Form, IPersonView
    {
        private PersonPresenter presenter = null;
        public PersonView()
        {
            InitializeComponent();

            presenter = new PersonPresenter(this); // V has property and DI will inject Presenter.. but let's make it simple for now. 
        }

        public void SetData(Person person)
        {
            if (person != null)
            {
                firstNameTextBox.Text = person.FirstName;
                lastNameTextBox.Text = person.LastName;
            }
        }      

        private void saveButton_Click(object sender, EventArgs e)
        {            
            presenter.Save(new Person() { FirstName = firstNameTextBox.Text,  LastName = lastNameTextBox.Text });
        }
    }

Presenter

public class PersonPresenter
    {       
        private readonly IPersonView view;

        public PersonPresenter(IPersonView view)
        {
            this.view = view;

            var person = new Person() { FirstName = "John", LastName = "Black" };
            view.SetData(person);
        }

        public void Save(Person person)
        {
            //Save
        }
    }

 Question: How should we change this to MVVM pattern? Do we just need to change the name PersonPresenter to PersonViewModel? 

I would like as below ~

Model (no change)

 public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

Note: IPersonView is removed.

View (Bind to Person property and Save Command from ViewModel)

 public partial class PersonView : UserControl
    {
        public PersonView()
        {
            InitializeComponent();
            this.DataContext = new PersonViewModel();
        }
    }

ViewModel

 public class PersonViewModel //INP
    {
        public DelegateCommand SaveCommand { get; set; }

        public PersonViewModel()
        {
            SaveCommand = new DelegateCommand(OnSaveCommand);
        }
        private Person person = new Person();

        public Person Person
        {
            get { return person; }
            set { person = value; }
        }

        public void OnSaveCommand()
        {
            
        }
    }

Please feel free to let me know if I'm in wrong direction.  I understand that having view reference make life easier for some cases but we are not discussing about difficulties. I used MVVM + MVP in real project. But I know that I have mixed intentionally. Anyway, I''m not going to tell people that this is a MVVM. 


My previous questions ~ 

1. Do you think that it's okay to set like iview.SetData or iview.SetSomething from ViewModel? Could you please give me an example for setting view from ViewModel via an interface? 

2. How does it helpful to set the view from the constructor of View Model? Example please. 


Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Michael Sync

unread,
Feb 5, 2010, 7:59:16 AM2/5/10
to wpf-di...@googlegroups.com
Thanks. Bill. I will check Onyx code this weekend. I really understand that we can mix the pattern based on scenario or Me and some UK developers from my office even created one pattern which is the mixed of MVP + MVC + PersentationModel that we need to our requirement and to make our developer's life more easier. 

Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Daniel Vaughan

unread,
Feb 5, 2010, 10:29:55 AM2/5/10
to WPF Disciples
Jer, I had a play around with this at lunch today, and did a brief
write up.

http://danielvaughan.orpius.com/post/ViewModel-Active-Awareness-in-a-Prism-Based-Application.aspx

Cheers,
Daniel

On Feb 5, 2:00 am, Jeremiah Morrill <jeremiah.morr...@gmail.com>
wrote:


> Daniel, I'm not sure I follow.  The IView (and VM) are both instantiated by
> IoC.   IActiveAware is only used by the IRegionManager, but implemented on
> your view.  I need to let the VM know when the RegionManager sets
> IActiveAware.IsActive has changed.  So the way I understand my options are I
> could use a message bus in code-behind, MVP style communication back to the
> VM in code-behind, or inherit my IView from IActiveAware and hook into the
> IsActiveChanged event from the VM (which I guess would be the same as MVP
> style).
>
> -Jer
>

> ...
>
> read more »

Michael Sync

unread,
Feb 5, 2010, 10:35:24 AM2/5/10
to wpf-di...@googlegroups.com
Great, Daniel.. 


Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Daniel Vaughan

unread,
Feb 5, 2010, 10:48:43 AM2/5/10
to WPF Disciples
Thanks Michael.
Yes, I used the idea for the ActiveAwareUIElementAdapter from that
article.


On Feb 5, 4:35 pm, Michael Sync <mchls...@gmail.com> wrote:
> Great, Daniel..
>

> I also like that posthttp://kentb.blogspot.com/2009/05/mvvm-infrastructure-activeawarecomm...


>
> Thanks and Best Regards,
> Michael Sync
>
> Don't go the way life takes you.
> Take life the way you go
>
> http://michaelsync.net
>

> On Fri, Feb 5, 2010 at 11:29 PM, Daniel Vaughan <dbvaug...@gmail.com> wrote:
> > Jer, I had a play around with this at lunch today, and did a brief
> > write up.
>

> >http://danielvaughan.orpius.com/post/ViewModel-Active-Awareness-in-a-...

> ...
>
> read more »

Glenn Block

unread,
Feb 5, 2010, 12:08:05 PM2/5/10
to wpf-di...@googlegroups.com
Yes, you can with an attached behavior or something similar. You just
can't easily get it injected into the VM's ctor if you use IoC.

Now some containers allow paramterized construction meaning at the
time you call resolve, you can explicitly pass in params to the ctor
like the IView even though the container is building it up. Not all
support ths though.

Glenn Block

unread,
Feb 5, 2010, 12:14:58 PM2/5/10
to wpf-di...@googlegroups.com
Pretty much, though you don't really need a the view to access the concrete.

What I would do off my head is have an extension method possibly
called like InitializeViewModel which access the DC, casts it to an
IViewModel and calls SetView on it passing in the current view.

The VM itself would implement a boiler plate IViewModel which has a
single member, SetView. Alternatively you might be able to use the
Dynamic keyword to just set it and assume the member is there, thus no
interface required.

The advantage of this approach is the View has no 'Hard' knowledge of the VM.

On 2/5/10, Michael Sync <mchl...@gmail.com> wrote:
> Hi Glenn,
>
>
>
>>>MVP, Views binds to data hanging off of the Presenter, not the Presenter
> itself. UI gestures are routed through the presenter via event handlers on
> the view which invoke the Presenter.
>>>>ViewModel, View binds directly to the ViewModel itself. This possible
> because UI gestures can also be handled through binding ie through
> commanding.
>
> I think this is the flow from View to Presenter. I understand that View and
> ViewModel are communicated via binding or commanding. The question is that
> ... Do you set the view from ViewModel via interface

> like*iview.SetSomething() from ViewModel
> *?


>
> Let's make it more clear.. I'm sure that it's more clear for all of us to
> see the code.
>
> Let's create one example:
>
> --- User can enter First Name and Last Name in UI.
> --- User can save the data.
>

> Here is the *MVP patten that I understand*.
>
> *Model *


>
> public class Person
> {
> public string FirstName { get; set; }
> public string LastName { get; set; }
> }
>

> *Interface of View*


>
> public interface IPersonView
> {
> void SetData(Person person);
> }
>

> *View*


>
> public partial class PersonView : Form, IPersonView
> {
> private PersonPresenter presenter = null;
> public PersonView()
> {
> InitializeComponent();
>
> presenter = new PersonPresenter(this); // V has property and DI
> will inject Presenter.. but let's make it simple for now.
> }
>
> public void SetData(Person person)
> {
> if (person != null)
> {
> firstNameTextBox.Text = person.FirstName;
> lastNameTextBox.Text = person.LastName;
> }
> }
>
> private void saveButton_Click(object sender, EventArgs e)
> {
> presenter.Save(new Person() { FirstName = firstNameTextBox.Text,
> LastName = lastNameTextBox.Text });
> }
> }
>

> *Presenter*


>
> public class PersonPresenter
> {
> private readonly IPersonView view;
>
> public PersonPresenter(IPersonView view)
> {
> this.view = view;
>
> var person = new Person() { FirstName = "John", LastName =
> "Black" };
> view.SetData(person);
> }
>
> public void Save(Person person)
> {
> //Save
> }
> }
>
> Question: How should we change this to MVVM pattern? Do we just need to
> change the name PersonPresenter to PersonViewModel?
>
> I would like as below ~
>

> *Model (no change)*


>
> public class Person
> {
> public string FirstName { get; set; }
> public string LastName { get; set; }
> }
>
> Note: IPersonView is removed.
>

> *View (Bind to Person property and Save Command from ViewModel)*


>
> public partial class PersonView : UserControl
> {
> public PersonView()
> {
> InitializeComponent();
> this.DataContext = new PersonViewModel();
> }
> }
>

> *ViewModel*

Glenn Block

unread,
Feb 5, 2010, 12:17:40 PM2/5/10
to wpf-di...@googlegroups.com
You would still bind the VM to the VIew, it is no different from that
perspective.

The only difference is the view impements an interface that the VM can
use to talk back to it for situations where binding is not suffucient.

I am not at all advocating we throw out binding, this is for special
case use only such as chatty communication from the VM to the view.

On 2/5/10, Michael Sync <mchl...@gmail.com> wrote:

> Hi Glenn,
>
>
>
>>>MVP, Views binds to data hanging off of the Presenter, not the Presenter
> itself. UI gestures are routed through the presenter via event handlers on
> the view which invoke the Presenter.
>>>>ViewModel, View binds directly to the ViewModel itself. This possible
> because UI gestures can also be handled through binding ie through
> commanding.
>
> I think this is the flow from View to Presenter. I understand that View and
> ViewModel are communicated via binding or commanding. The question is that
> ... Do you set the view from ViewModel via interface

> like*iview.SetSomething() from ViewModel
> *?


>
> Let's make it more clear.. I'm sure that it's more clear for all of us to
> see the code.
>
> Let's create one example:
>
> --- User can enter First Name and Last Name in UI.
> --- User can save the data.
>

> Here is the *MVP patten that I understand*.
>
> *Model *
>

> public class Person
> {
> public string FirstName { get; set; }
> public string LastName { get; set; }
> }
>

> *Interface of View*


>
> public interface IPersonView
> {
> void SetData(Person person);
> }
>

> *View*


>
> public partial class PersonView : Form, IPersonView
> {
> private PersonPresenter presenter = null;
> public PersonView()
> {
> InitializeComponent();
>
> presenter = new PersonPresenter(this); // V has property and DI
> will inject Presenter.. but let's make it simple for now.
> }
>
> public void SetData(Person person)
> {
> if (person != null)
> {
> firstNameTextBox.Text = person.FirstName;
> lastNameTextBox.Text = person.LastName;
> }
> }
>
> private void saveButton_Click(object sender, EventArgs e)
> {
> presenter.Save(new Person() { FirstName = firstNameTextBox.Text,
> LastName = lastNameTextBox.Text });
> }
> }
>

> *Presenter*


>
> public class PersonPresenter
> {
> private readonly IPersonView view;
>
> public PersonPresenter(IPersonView view)
> {
> this.view = view;
>
> var person = new Person() { FirstName = "John", LastName =
> "Black" };
> view.SetData(person);
> }
>
> public void Save(Person person)
> {
> //Save
> }
> }
>
> Question: How should we change this to MVVM pattern? Do we just need to
> change the name PersonPresenter to PersonViewModel?
>
> I would like as below ~
>

> *Model (no change)*


>
> public class Person
> {
> public string FirstName { get; set; }
> public string LastName { get; set; }
> }
>
> Note: IPersonView is removed.
>

> *View (Bind to Person property and Save Command from ViewModel)*


>
> public partial class PersonView : UserControl
> {
> public PersonView()
> {
> InitializeComponent();
> this.DataContext = new PersonViewModel();
> }
> }
>

> *ViewModel*

Glenn Block

unread,
Feb 5, 2010, 12:19:04 PM2/5/10
to wpf-di...@googlegroups.com
Guess I need to do a blog post as well, there goes the day!

Bill Kempf

unread,
Feb 5, 2010, 12:22:13 PM2/5/10
to wpf-di...@googlegroups.com
On Fri, Feb 5, 2010 at 12:08 PM, Glenn Block <glenn...@gmail.com> wrote:
> Yes, you can with an attached behavior or something similar. You just
> can't easily get it injected into the VM's ctor if you use IoC.

Onyx enables this today, and it will be the default MO in the next
version, so it's very possible to create the VM using an IoC container
when doing View first by using an attached behavior.

> Now some containers allow paramterized construction meaning at the
> time you call resolve, you can explicitly pass in params to the ctor
> like the IView even though the container is building it up. Not all
> support ths though.

There's three routes to enabling this, all depending on the support of
the specific container used.

1. Child containers with the IView registered.
2. Parameterized construction.
3. Fallback to your own construction mechanism that uses the IoC
container to resolve the other constructor parameters.

Glenn Block

unread,
Feb 5, 2010, 12:35:28 PM2/5/10
to wpf-di...@googlegroups.com
Yes, I didn't want to get into child containers though they do work,
but they add perceived complexity.

Attached behavior today seems like the best way to go.

As a side note on child containers, now that I am on the CLR, one of
the things I want to tackle is a general mechanism for scoping objects
within .NET.

If we had such a mechanism we could easily define scope boundaries,
where a shared vm instance / view instance could easily be accessed by
logical children without being dependent on the visual tree,or even
being UI compomnents. My initial feeling is something much lighter
than app domains ie no remoting required.

I have no idea what it will look like, but I think it will help
signficantly with complex MVVM scenarios, especially when the graph is
built up incrementally such as happens with a View-First style.

On 2/5/10, Bill Kempf <wek...@gmail.com> wrote:

--

Bill Kempf

unread,
Feb 5, 2010, 12:38:03 PM2/5/10
to wpf-di...@googlegroups.com
Child containers aren't that bad, and the beauty is that any
complexity they do bring is entirely hidden behind the implementation
of the attached behavior.

I'm quite interested in your scope boundaries idea, though.

Glenn Block

unread,
Feb 5, 2010, 12:47:31 PM2/5/10
to wpf-di...@googlegroups.com
In thenselves they are not bad, though they do get abused.

I am firm believer though that once a problem starts to become so
pravelent, it's good to have a more specific / inherent solution.

The problem with the containers is just the extra config work. If you
had something like scope it would be more transparent.

Jeremiah Morrill

unread,
Feb 5, 2010, 1:14:43 PM2/5/10
to wpf-di...@googlegroups.com
Daniel, very cool...and very thorough!   Thanks a bunch too!


-Jer

Michael Sync

unread,
Feb 5, 2010, 9:16:32 PM2/5/10
to wpf-di...@googlegroups.com
>>The advantage of this approach is the View has no 'Hard' knowledge of the VM

Yeah. We can use IVM in View as well.. But as we all already know how View can talk to VM, I left that part. I'm trying to show my understand about how VM can talk to View in MVP pattern and MVVM and I'm also trying to understand the use case that what we can do after using SetView in VM. 

>>Guess I need to do a blog post as well, there goes the day!

Thanks, Gleen. Love to see the new blog post... 

Yes. We can use an interface of View where binding is not sufficient. But Would it be cool if we use attached property or dependency property or behivor or something instead of IView interface? 

Please add more examples that shows the binding is not sufficient so we have to use an interface of View.. :) 


Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Glenn Block

unread,
Feb 6, 2010, 2:26:43 AM2/6/10
to wpf-di...@googlegroups.com
Hi Michael
 
Attached property won't help you if you are calling a parameterized method or a method with a return value.
 
For example, let's say you want a popup to gather some input from the user. You could have a IsPopupVisible property hanging off the VM and bind some type of trigger to it. Then when the message is entered, you bind back from the popup's VM to the property on the main VM that represents the text value. You would then also need to reset IsPopupVisible. Alternatively you could use message passing, but then you need to make sure once the save is complete, that you send a message back to the VM (or directly invoke it with the value). Now compare that to simply calling a GetInputTextMethod on the IView which returns the text immediately after the popup is closed. Isn't that far simpler then all the indirection?
 
Thanks
Glenn

Michael Sync

unread,
Feb 6, 2010, 2:49:35 AM2/6/10
to wpf-di...@googlegroups.com
Hi Glenn,

>>You could have a IsPopupVisible property hanging off the VM

Why? Can we just have a command in ViewModel and call the IDisplayPopupService or IDialogService or something for that case? 

I would do the following in ViewModel. 

For example:

private void OnShowPopupCommand(){

var result = displayPopuupService.Show("The list of parameters that you want to pass");


FirstName = result.FirstName;
LastName = result.LastName; 

}



Thanks and Best Regards,
Michael Sync

Don't go the way life takes you.
Take life the way you go

http://michaelsync.net


Glenn Block

unread,
Feb 6, 2010, 2:51:11 PM2/6/10
to wpf-di...@googlegroups.com
IsPopupVisible is not the replacement for the command, I was assuming you would have a command. IsPopVisible is a property thatthe VM would set when the command was fired in order to display the popup itself.
 
Yes you could inject an IDisplayPopupService. I am using the view as a service in this sense. For a simple popup (like a message box) that gather's input I would probably use such a service. If however there were specific elements in the View that needed to be shown, then using IDisplayPopupService would be a pain since it would have to somehow get passed references to the speicfic view elements that get manipulated. In the IView case when I call the DisplayPopup method because the code lives in the view it has full access to it's elements.
 
Regardless we are agreeing that there are interactions between the VM and the UI that are not able to be handled through binding :-) Calling IDisplayPopupService is outside of the binding context.
 
Glenn

Reply all
Reply to author
Forward
0 new messages