Best way to pass data from code-behind to view model when using strict MVVM

fefferonifefferoni Member ✭✭

Scenario:
I'm using a barcode scanner API in my view which seems to require me to hook up an event in the code-behind file as the only way to get the scanned barcode. When the barcode is scanned I want to pass the data on to the view model but since I want to follow the MVVM pattern I don't want a reference to the view model from my code-behind.

Right now I solved it by using the built in MessagingCenter.
Since the subview is showing within another view, there is no navigation taking place where I can pass on data from one vm to another.

Question:
Is MessagingCenter the best solution for this?

Sub question:
What is the best way to pass data between two view models for views showing at the same time (no navigation occurs)? I'm using MessagingCenter for this too right now.

Best Answer

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    I'm using a barcode scanner API in my view which seems to require me to hook up an event in the code-behind file as the only way to get the scanned barcode.

    That's odd... but hey every maker is different.

    Is MessagingCenter the best solution for this?

    Its not aweful.

    You could also raise a Command such as BarcodeReceivedCommand with the CommandParameter being the barcode value. Then have a handler for that command do its thing.

    pass data between two view models for views showing at the same time

    Could both views use the same VM? That cuts down on a lot of complexity you're seeing.

  • fefferonifefferoni Member ✭✭

    Hey, thanks for this quick reply.

    @ClintStLaurent said:

    I'm using a barcode scanner API in my view which seems to require me to hook up an event in the code-behind file as the only way to get the scanned barcode.

    That's odd... but hey every maker is different.

    I guess it has to do with the way we implemented it. It is a custom view with specific platform renderers.

    Is MessagingCenter the best solution for this?

    Its not aweful.

    You could also raise a Command such as BarcodeReceivedCommand with the CommandParameter being the barcode value. Then have a handler for that command do its thing.

    Sounds like a much better solution. But I'm guessing this involves some kind of custom behavior? I've not created any on my own yet. Will have to look into it. Good advice.

    pass data between two view models for views showing at the same time

    Could both views use the same VM? That cuts down on a lot of complexity you're seeing.

    That would be great, but right now I'm using a view model locator to take care of all the dependencies and automatically bind the correct VMs to the views. I would have to brake this pattern if I wanted the same VM for multiple views.

Sign In or Register to comment.