How to call UI Controls method from ViewModel (MVVM)?

I want to call AutoComepleteBox s PopulateComplete () from ViewModel as I call it?

+4
source share
3 answers

Behavior using System.Windows.Interactivity is a great way to do this.

Take a look at this - http://julmar.com/blog/mark/?p=34 - in this case it uses it for a watermark, but you can easily adapt the behavior ... I often refer to this blog post as starting point.

The main thing that you do is that you get access to those things that could not be events that you cannot connect to in the viewing model, it takes a few minutes to understand them, but one evening on the couch reading some blogs and MSDN and you will become a big fan!

+2
source

View should handle everything related to the user interface and view - ideally, you would PopulateComplete() from the view itself. Based on your comment on BrandonZeider's answer, I suggest you create an event in the ViewModel that will fire after the service method finishes, and put your call to PopulateComplete() in the handler for this event in the view.

Now you can use your ViewModel anywhere - if something needs to happen in the view when the service call ends, it can simply subscribe to a new event.

+1
source

There are several ways to do this, it just depends on what you are trying to do ... where are you trying to call PopulationComplete () in your ViewModel? For example, if you are in an instance of ICommand , you can pass it as a parameter, drop it, and call your method.

Based on your comment, I would approach this a little differently. This will be due to a number of workarounds due to control limitations.

Add an event listener to the view in the code behind, listening to the collection collection change event in your view model. Then you can call PopulateComplete () in the event handler. You will need a link to your ViewModel in your view for this.

Another option is to pass the link to the AutoComepleteBox to the ViewModel when the View loads (using EventTrigger) and stores the link in a private field. Then, when your web service call returns, use this link to call PopulateComplete ().

-1
source

Source: https://habr.com/ru/post/1346913/


All Articles