OnNavigatedTo() method is not triggered in Xamarin.Forms - xamarin

I have inherited my view model class from INavigateAware interface as below,
public class ViewModel : INavigationAware
{
public ViewModel()
{
}
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public void OnNavigatedTo(NavigationParameters parameters)
{
// some codes
}
}
And called that view model in the associated view(the page I have been navigated to)
public partial class Page1 : ContentPage
{
ViewModel viewModel;
public Page1()
{
InitializeComponent();
viewModel = new ViewModel();
this.Content = myview; //myview is my control like grid
}
}
Now my problem is when I navigate to this page(Page1), OnNavigateTo() method in ViewModel is not triggered. Please someone helps me how to make trigger OnNavigateTo() method.
Thanks in advance.

First thing first, check if you have AutowireViewModel parameter in your page class set to True.
Second, you should not assign view model yourself, prism will do that for you, when you call PushViewModel
Third there is well known limitation in prism:
https://github.com/PrismLibrary/Prism/issues/563
There is also workaround suggested:
Create interface:
public interface IPageNavigationAware
{
void OnAppearing();
void OnDisappearing();
}
Derive your ViewModel class from this interface.
In the Views code behind:
protected override void OnAppearing()
{
(BindingContext as IPageNavigationAware)?.OnAppearing();
}
protected override void OnDisappearing()
{
(BindingContext as IPageNavigationAware)?.OnDisappearing();
}
The problem with that is that OnAppearing/OnDissapparing are not reliable navigation methods and do not accept parameters, but rather page lifecycle methods. They do not indicate when a page has been navigated to or from. You can have instances where a parent page can be appearing at the same time as multiple child pages are appearing. This will be addressed when Xamarin provides a proper navigation API.

Related

Binding string with Button

I am trying to bind a string to a Button in pure C# (no XAML), but apparently I am doing it wrong, as the result of my code is that the button disappears.
I am defining my property as follows:
public string selectionString { get; set; }
And this is how I am binding the string to the button:
selectionString = "Hello";
selectionButton = new Button
{
TextColor = Color.Black
};
selectionButton.SetBinding(Button.TextProperty, "selectionString");
Children.Add(selectionButton);
I have tried to use BindingMode.TwoWay, but it doesn't work.
Of course, setting the text and removing the binding makes the button appear and work.
My need is just this: the button text should be the selectionString, and if this changes by an external event, so the button's text should change accordingly.
Am I missing something in how the binding works?
Bindings work against public properties on the view's binding context, and respond to INotifyPropertyChanged events firing. Hopefully this demonstrates for you.
public class MyViewModel : INotifyPropertyChanged
{
// Fire RaisePropertyChanged in the setter, I use Fody to weave this in
public string SelectionString {get;set;}
}
public class MyView : Page
{
protected override void OnBindingContextChanged()
{
if (BindingContext is MyViewModel)
{
this.SetBinding(Button.TextProperty, "SelectionString");
}
}
}

How to pass Data to different Views in MVVM Light?

I am kinda unclear on how to pass data to other views. I gathered there are 3 ways to do this but I not sure how to do 2 of them.
Send data through messenger(not sure if you can send objects otherwise I can see thing getting pretty messy if you have to send like 10 pieces of data or something like that along).
Somehow pass the data through the constructor of the new view model. I say "somehow" as I am unclear how to do that when using an IOC container(in this case the built in one).
Passing the data through a parameter. I seen a couple of tutorials that show you how to do navigation for the windows phone but none really talk about parameter passing. I am guessing this would still be an option.
From what I heard is that Option 1 is sort of the old way of doing it. Option 2 seems to be a newer way and better way to do it but I cannot find any examples on people showing how to do it.
I don't know how to do it because the Ioc should be creating the instance of the view so how do you pass in data into it when that data does not exist?
The two main ways I do this is:
1)Use the messenger:
Sender class:
public class TrafficLight
{
public string Color{get;set;}
public TimeSpand Duration{get;set;}
}
public class TrafficLightService
{
public void SendLight(TrafficLight light)
{
Messenger.Default.Send(light);
}
}
Receiver:
public class MyViewModel
{
public MyViewModel()
{
Messenger.Default.Register<TrafficLight>(DoSomethingWithTrafficLight);
}
private void DoSomethingWithTrafficLight(TrafficLight light)
{
}
}
What happens here is that the source object is using the Messenger as an event broker. Object A doesn't need to know about object B, they just both need to know about the messenger.
2)
Just use dependency injection:
public class TrafficLight
{
public string Color{get;set;}
public TimeSpand Duration{get;set;}
}
public class LightEventArgs:EventArgs
{
public LightEventArgs(TrafficLight light)
{
_light=light;
}
public TrafficLight Light{get{return _light;}}
}
public interface ITrafficLightService
{
void SendLight(TrafficLight light);
public event EventHandler<LightEventArgs> TrafficLightSet;
}
public class TrafficLightService
{
public void SendLight(TrafficLight light)
{
Messenger.Default.Send(light);
}
public event EventHandler<LightEventArgs> TrafficLightSet;
}
public class TrafficLightSenderViewModel
{
public TrafficLightSenderViewModel(ITrafficLightService trafficLightService)
{
_trafficLightService=trafficLightService;
_trafficLightService.Send(new TrafficLight{Color="Red"});
}
}
public class TrafficLightReceiverViewModel
{
public TrafficLightReceiverViewModel(ITrafficLightService trafficLightService)
{
_trafficLightService=trafficLightService;
_trafficLightService.TrafficLightSet+= TrafficLightNotification;
}
private void TrafficLightNotification(TrafficLightEventArgs args)
{
DoSomethingWithTheLight(args.Light);
}
}
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<ITrafficLightService, Design.TrafficLightService>();
}
else
{
SimpleIoc.Default.Register<ITrafficLightService, TrafficLightService>();
}
SimpleIoc.Default.Register<TrafficLightSenderViewModel>();
SimpleIoc.Default.Register<TrafficLightReceiverViewModel>();
}
public MainViewModel Sender
{
get { return SimpleIoc.Default.GetInstance<TrafficLightSenderViewModel>(); }
}
public MainViewModel Receiver
{
get { return SimpleIoc.Default.GetInstance<TrafficLightReceiverViewModel>(); }
}
}
This is a bigger example and more complex.
Lets walk through this step by step:
In MVVM Light we use the ViewModelLocator for 2 things: 1)To register all our viewmodels and services.
Provide a way to allow the View to get a viewmodel in XAML
When we try to resolve a ViewModel
SimpleIoc.Default.GetInstance<TrafficLightReceiverViewModel>();
SimpleIoc looks at whether the viewmodel has any dependencies. In our case we do, we need an ITrafficLightService for both our viewmodels. What happens is that SimpleIoc sees if it can resolve that class and, in the process, checks to see if ITrafficLightService has any dependencies that need resolving as well. If SimpleIoc can resolve the chain of dependencies required to instantiate your viewmodel it does so and then hands back a fully built object.

Windows Phone - Using generic class for PhoneApplicationPage

I have a Page which consist of AddPage.xaml and AddPage.xaml.cs. I want to create a generic class AddPage which extends from PhoneApplicationPage to outsource some repetitive code like Save or Cancel.
If I change the base class from PhoneApplicationPage to my new generic class, I get this error: Partial declarations of 'AddPage' must not specify different base classes.
To accomplish this you need to do the following.
First, create your base class
public class SaveCancelPhoneApplicationPage : PhoneApplicationPage
{
protected void Save() { ... }
protected void Cancel() { ... }
}
Then, your AddPage needs to be modified to inherit from the base class. The main places this is needed is within the code (AddPage.xaml.cs) AND within the xaml
Code:
public partial class AddPage : SaveCancelPhoneApplicationPage { ... }
Xaml:
<local:SaveCancelPhoneApplicationPage
x:Class="MyPhone.Namespace.AddPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyPhone.Namespace"
<!-- other xaml elements -->
</local:SaveCancelPhoneApplicationPage>
UPDATE: Info added based on comments
If you need to have generic like functionality and you must use the Page to do this (rather than a ViewModel) then you can still do this using generic methods
public abstract class SaveCancelPhoneApplicationPage : PhoneApplicationPage
{
protected override void OnNavigatedTo(blaa,blaa)
{
var obj = CreateMyObject();
obj.DoStuff();
}
// You should know what your objects are,
// don't make it usable by every phone dev out there
protected MyBaseObject MyObject { get; set; }
protected T GetMyObject<T>() where T : MyBaseObject
{
return MyObject as T;
}
}
public class AddPage : SaveCancelPhoneApplicationPage
{
public AddPage()
{
MyObject = new MyAddObject();
}
}
In order to outsource some functions you just declare some add class which does the common work. Having another page doesn't do that work.
public class Add
{
public bool SaveContent(string filename, string content)
{
....//some content
return true;
}
public string ViewContent(string filename)
{
string content="";
.....
return content;
}
}
Add this part of code where you thought it is redundant.
Add obj=new Add();
obj.SaveContent("myfile.txt","Hello.This is my content.");
string content("myfile.txt");
Tell me if this is what you intend or not.

Why is an item in the ViewBag not propagated to the _Layout page?

I have a SiteNavigation class that is being updated in the Initialize event of my base controller e.g.
[Serializable]
public class SiteNavigation
{
public SiteNavigation()
{
IsSummarySelected = true;
}
public Model.Dtos.Folder[] Folders { get; set; }
public bool IsSummarySelected { get; set; }
}
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
var siteNavigation = new SiteNavigation();
siteNavigation.Folders = GetMeMyFolders() as Folder[];
ViewBag.SiteNavigation = siteNavigation;
}
and in the controller the IsSummarySelected property is changed to this value.
ViewBag.SiteNavigation.IsSummarySelected = false;
When I access the property in the _Layout file with this line of code, the value is ALWAYS true. It's as if the nav object is being New'd up again and the constructor is setting it to true.
#if (ViewBag.SiteNavigation.IsSummarySelected)
I've tried casting the nav object back to a variable and setting the property that way too, no dice. Any help would be appreciated.
Call me baffled!
Thank you,
Stephen
I just copy pasted your code into my sample mvc project, and changing IsSummarySelected in my action correctly was reflected in the _Layout file. Are you certain your controller's assignment is getting hit, and you're not reassigning it afterwards somewhere else?
Edit: Your issues are an example of why I think it's a bad idea to use ViewBag for anything other than a localized quick fix. Debugging dynamic global objects is no fun. Refactoring suggestion: Make a site Navigation property in your base controller
SiteNavigation siteNavigation;
public SiteNavigation SiteNavigation
{
get
{
return siteNavigation;
}
set
{
siteNavigation = value;
}
}
and replace all references to ViewBag.SiteNavigation with this. Then create a custom WebViewPage and put in it.
public SiteNavigation SiteNavigation
{
get
{
return ((BaseController)ViewContext.Controller).SiteNavigation;
}
}
This won't fix your problem, but now you can just stick breakpoints on the get and set properties of SiteNavigation, and it should be very easy to debug your issue now.
I fill my TempData["SplitterIsCollapsed"] when Filters are invoked then via OnResultExecuting method. Additionally i fetch a property state from my UserContext class, which is registered only once per session: builder.RegisterType().As().CacheInSession(); .
Basic info: I use DependcyInjection!
Assignment of the Filter to the Controller:
Controller:
[LayoutTempData]
public class HomeController : Controller
{
//....
}
FilterAttribute class:
namespace MyProject.Web.Infrastructure.Filters
{
public class LayoutTempDataAttribute : ActionFilterAttribute
{
private readonly IUserContext _userContext;
public LayoutTempDataAttribute()
{
_userContext = DependencyResolver.Current.GetService<IUserContext>();
}
public override void OnResultExecuting(ResultExecutingContext context)
{
if (context.Controller.TempData.ContainsKey("SplitterIsCollapsed"))
context.Controller.TempData["SplitterIsCollapsed"] = _userContext.LayoutInformation.SplitterIsCollapsed;
else
context.Controller.TempData.Add("SplitterIsCollapsed", _userContext.LayoutInformation.SplitterIsCollapsed);
}
}
}
The Splitter part of the _Layout.cshtml looks like:
#{Html.Telerik().Splitter().Name("Splitter1")
.Panes(panes =>
{
panes.Add()
.Size("300px")
.Collapsible(true)
.Collapsed((bool)TempData["SplitterIsCollapsed"])
.Content(<div>asdfasdf</div>);
panes.Add()
.Collapsible(false)
.Scrollable(false)
.Content(<div>content2</div>);
})
.Render();
}

BlackBerry - Fun with FieldManagers

I am trying to make a View class that provides a Horizontal or Vertical layout depending on how it is created. I'm using a delegate to achieve this.
class View extends Manager {
private Manager mDelegate;
public View(Manager inDelegate) {
mDelegate = inDelegate;
// the delegate is the only child of "this" manager.
super.add(mDelegate);
}
public void add(Field f) {
// all other children go into the delegate.
mDelegate.add(f);
}
// other methods that also delegate
}
When I instantiate a View object I pass in a Horizontal or Vertical field manager and then delegate calls to that. This is kinda what the Screen class does in blackberry.
Actually I am looking at the blackberry docs for Screen to see what calls it delegates (so I can emulate that) and I notice calls like this in Screen...
protected boolean keyChar(char c, int status, int time)
Delegates key generation event to the controlled field with focus.
This method invokes Manager.keyChar(char, int, int) on this screen's delegate manager.
So then it immediately dawns on me, how in the world are they calling a protected method on the screen's delegate? Or are the docs wrong and this method isn't delegated?
Anyone know how they accomplish this?
Reminding myself what protected means:
A protected method can be called by
any subclass within its class, but not
by unrelated classes.
This doesn't directly answer your question, but could you extend Screen (API here) instead of Manager and then call super(mDelegate) in your constructor? Then presumably whatever magic is necessary will just work?
Aside from that I would just suggest you try it and see if you can override the supposedly protected method!
I managed to work out a solution to this problem with help from some other SO questions.
My solution is to create an interface that provides the public access points for the protected methods and then subclass the Manager class and mix in that interface. The public method will then call its super's protected method.
Then the View class is then passed one of these Manager subclasses.
public interface ManagerDelegate {
Manager asManager();
// Provide public access points to any protected methods needed.
void doProtectedMethod();
}
public HorizontalDelegate extends HorizontalFieldManager implements ManagerDelegate {
public Manager asManager() {
return this;
}
public void doProtectedMethod() {
// call the Manager's protected method.
protectedMethod();
}
}
public VerticalDelegate extends VerticalFieldManager implements ManagerDelegate {
public Manager asManager() {
return this;
}
public void doProtectedMethod() {
// call the Manager's protected method.
protectedMethod();
}
}
public class View extends Manager {
private final ManagerDelegate mDelegate;
public View(ManagerDelegate inDelegate) {
mDelegate = inDelegate;
}
protected void protectedMethod() {
// Call into our delegate's public method to access its protected method.
mDelegate.doProtectedMethod();
}
public void publicMethod() {
// For public delegated methods I can just get the Manager instance from
// the delegate and call directly.
mDelegate.asManager().publicMethod();
}
}

Resources