How to add to an ObservableCollection from a different view? - xamarin

(I'm using Prism Dryloc) My application consists of two views. The first contains a single list view displaying strings and the second - an entry and a button.
The listview is bound to an observable collection in the first page's View Model. How can I add to the observable collection from a different view?

Great question! You're essentially trying to pass data between views, and there's several ways of passing data between Views in Xamarin.Forms.
The two ways that seem relevant for your case:
Either making the ObservableCollection a public static object (so there's only one global instance of it). Not recommended.
The better way is to use the messaging center so that the second page publishes an event when the button is pressed, that the first page is subscribed to. And it passes that information that gets added to the list.
If these don't work, elaborate your use case and I'll suggest some more

Related

Cocoa bindings issue with three tableviews

im a osx-dev noob that is trying to build an application with three table views that will show the content of a core data store entity. But each table view is filtered on the attribute "status" of the entity.
the problem occurs when i also want to show the selected entity in textfields. I'm using three different array controllers with different fetch predicates. But in a textfield i can only bind the value to one array controller.
should i ditch the bindings and do it all programaticly or is there a simple solution to this? :)
here is an screenshot so you can grasp my app description.
Keep bindings to populate the text fields if it satisfies what you want to do with this GUI. I'd add an NSObjectController to control the one entity those fields represent. If you want the user's changes to those fields persisted, bindings are still awesome.
But I think with three tables that might control what's displayed in the text fields, you're going to need to have some sort of non-binding glue code that determines which of the tables wins. You can probably do everything you want by implementing some of the NSTableViewDelegate protocol.
If the text fields should display the last entity that the user clicked in any of the tables, simply have each table call the same tableViewSelectionDidChange delegate function. All three tables could have the same delegate. You can then call setContent on the NSObjectController from that function.
You could also use similar glue code to prevent more than one selection in any of the three tables, by having the same delegate function deselect everything in the other tables either through the view or the controller. But that's up to you and needs consideration of whether you want multiple selection, etc.

When to use MVVM (i.e. Knockout.js) or simply return an EditorTemplate object from Controller action

In cases where new items need to be added to a list via ajax, what is the biggest benefit of using something like Knockout.
So far what I have been doing is, on my view, use an editortemplate (with asscociated viewmodels) to render a list of items. Then to add a new item, I make a request to an action that loads a server-side viewmodel, and returns an EditorTemplte object which just gets appended to the list. Like this:
return Json(new { this.RenderPartialViewToString("MyEditorTemplate", model) });
The knockout way of doing things requires the implementation of another view model to display items, and then another template to display it. But doing it this way requires duplication of code since the view model has to be represented in 2 places: in the cserver side code and then the view for the knockout viewmodel. Isn't that bad practice?
Am I missing something, or understanding the purpose of knockout and MVVM?
The biggest benefit that you will see from Knockout is that you will not need to hit the server in order to add a new item to your list - everything happens client side. This has multiple benefits including:
You reduce load on your server.
You improve the end-user's experience.
You can keep multiple elements on the page up-to-date with your model without any server interactions.
Two great examples of this can be found at these Knockout tutorials:
Working with Lists and Collections
Loading and Saving Data
As far as duplicating code, if you take a look at those two tutorials, you'll notice that you don't need to duplicate code. For example:
Create a view to display your entire list.
To add a new item to the list, create a partial view that you load when you add a new item to the page - that partial view is bound to Knockout
When you submit the entire form, everything in that list will be submitted - including those items you added via Knockout.
Your ViewModel will be specific to your list item (you don't need to create an entire ViewModel for everything, necessarily). And your view is specific to a single list item.
Hope that's clear. Knockout is pretty straightforward and they have some great documentation and tutorials to help you move forward.
IMHO, the following is cleanest option for the architecture of knockout and asp mvc mixed together.
Have your ASP.net acting as a webservice and have knockout control all your view templating and logic.
Otherwise, yes there will be potential replication of viewmodels and having to refactor both front and backend code when you need to change your model.

Backbone.js Use View to Manipulate Another View

My question is mostly conceptual about Backbone.js, but I can mock up some code if my question is unclear.
Consider a case where I have 2 sections on a website. A list of items as one view and another view that has a dropdown to select how the list of items should be sorted. Obviously, the list of items is associated with a collection of models that stores the actual data that populates the list. But I'm unsure the best approach for triggering the collection to be sorted differently when the other view's dropdown changes. Should I be changing the actual order of the collection, or just render the view in the order that I want in the view?
Also, is it a good idea to use a model for the dropdown to keep track of the state of the dropdown, and bind the list of items view to that model so that I know when to rerender the list of items?
You could take several roads here. Here's a few:
Use a router. The router would hold your views, or at least the top-level view (cleaner), and your dropdown view would trigger a route change, which would pass the information along to the view. Best if you want clean URLs.
Make a pointer to the list view in the dropdown view. When the dropdown view receives the change event, it explicitly tells the list view to update. (IMO a terrible approach, but listed here for completeness.)
Back everything with models. (Like you suggest in your last question.) The dropdown view would be backed by a model, and the list view could bind to that model's events. (Again, the list view still has to know about the dropdown model—not ideal.)
Make an event manager. When your dropdown recevies a change, you trigger 'sort' and anything that cares can listen to that event. This isn't a trivial solution but isn't overly complex either. Your list view could then register its intent to listen to the sort event with the event manager, thereby abstracting the actual view inside the event manager and away from the dropdown view.
1 & 4 are effectively the same thing, just depending on whether you want a router or not.
Basically my heuristic with these sorts of scenarios is "nothing should know about things it doesn't need to know about." Applied here, that means that your views shouldn't know about each other.

Updating Controls from Multiple Pages on Windows Phone

All, I am new to Windows 7 Phone. My situation is that I have a main page which contains a ScrollViewer which in turn houses a StackPanel. I want to populate this StackPanel with multiple sub-StackPanels (at runtime) which are to hold an Image Thumb nail a hyperlink and some basic information about the image.
This is all good when I do this from the main page, but I want to know how to update this control (which is on the main page), but from any page other than the main page. I would like to know what is considered best practice for updating a page's control (like that outlined above) from another page.
Obviously there are a number of ways to pass data between pages
PhoneApplicationService.Current.State["yourparam"] = param
NavigationService.Navigate(new Uri("/view/Page.xaml", UriKind.Relative));
then in other page simply
var k = PhoneApplicationService.Current.State["yourparam"];
and many others. But what is best practice for updating a generic control from a different page?
Note: There are many question about data access and passing between pages.
Passing data from page to page
How to pass the image value in one xaml page to another xaml page in windows phone 7?
Passing image from one page to another windows phone 7
and more. This is not what I am asking.
If I understand your question correctly, you are trying to update a control which is on for example MainPage.xaml from another page for example Page2.xaml.
As far as I know there is no way to reach a pages controls from another page, and that seems unnecessary for the cases that I can think of.
The method used to achieve what you are trying is usually done by triggering an action (like the press of a button ) and passing a parameter to the page you are trying to update the control. And on that page's onnavigatedto event (or viewmodel constructor if you are using the MVVM pattern), update your control based on the passed parameter.
If your update is based on data then the best practice is to bind an observable collection or an object that extends the INotifyPropertyChanged (basically any object that can signal that one of their property changed to the ui) and change the data based on the parameter that is passed.
If these two pages somehow are visible at the same time and there is no navigation needed between them( like a popup or sliding menu kind of ui) then you can make the page that you are showing in the popup a usercontrol, and reach to the parent's controls by this.Parent.
I can be more helpful if you give more specifics about your app's flow.
The MVVM pattern would be a good way to go. Saying MVVM is too complicated for small teams isn't exactly accurate - the purpose of MVVM is to decouple Silverlight or WPF code. Using the codebehind of a Silverlight page to directly access data creates coupling in your code and accrues technical debt. Whether you're one developer or 100, if your UI is coupled with your data classes, if you have to change your data classes, you will have to make changes to every UI element that uses those classes. This takes longer and makes your application more difficult to change.
MVVM makes it so your UI (the View) doesn't know anything about the data (your Model). The ViewModel is the code in between that the UI can bind to, and which manages events in the UI that need to be persisted to the Model, and also changes in the Model that need to be represented in the View. For this reason, it handles events, and that's what it sounds like you need in your code - an event that can exist off of the codebehind, that can update the Views bound to it when the data changes. If you have two pages, then an event on one of the pages will be sent to the ViewModel, which will make a change to the Model (data) if necessary, and pass it back to the ViewModel. The ViewModel would then update any of the UI elements (Views) bound to that piece of data.
There's a REALLY good demonstration of how to implement the MVVM design pattern here
. The guy goes through and takes a typical WPF application (just like Silverlight), where the UI codebehind implements event handlers that directly access data, and refactors it using the MVVM pattern.

Setting DataContext in UserControl from ViewModel

I have a View that contains a Listbox. I'll call it CityListingPage.xaml. This list page has a CityListingViewModel, that is binded with the View like somewhat like this:
DataContext="{Binding CityListing, Source={StaticResource Locator}}"
This works nicely. Now I what to change my page to a Pivot Control, where the Pivot Items, would be instances of CityListingViewModel, but obviously with different constructor data (ie. Country)
I extracted the ListBox into a UserControl. Now I'm struggling how to make this work so that for each list I get a new instance of the CityListingViewModel.
I tried creating in the ViewModelLocator a collection of CityListingViewModels but how do I pass the a CityListingViewModel instance to the UserControls DataContext?
Perhaps there is a different, better way of doing this?
Without seeing your code, I'm going to do a little guessing, but I think you can do it directly via data binding. Since each pivot item is getting an instance of CityListingViewModel, you can just pass that binding along to the UserControl:
If you post a little more code showing what you're trying to do, we might be able to be of more help.
The following are two answers for using a collection to create panorama pages. But I am quite sure that the approach can be adapted to pivot pages:
Dynamically add eventtocommand actions to a listbox
Static and dynamic panorama items in a panorama wp7 mvvm
The second post should be more relevant.
If you are thinking of partitioning the same data over multiple views on a pivot page then I would suggest NOT using several view models, especially if it is the same datasource you are using for all the data.
Simply have a parameter which each view would bind to and use Linq to control what data is visible to that parameter.
So you will have the variable which will contain all the data to be displayed and one parameter per view querying that data.

Resources